Search code examples
javafloor

Force integer division on a double?


I have

x /= y;

Where x & y are both double

I would like x to be the integer part of x/y , how do I do this?

I have tried

x /= y;
x = x.intValue();

But am receiving a double cannot be dereferenced error in TIO which I presume means the double x does not have that method

IO x = x\y: Carry out float division then round towards -∞

Sample table

NB all I'm after is to change this code to add in floor division with \


Solution

  • x = java.lang.Math.floor(x/y);
    

    Relying on some Math function is arguably the best choice. "Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer."

    If you need the symmetric version (truncation towards zero), you'll have to handle negative quotients:

     floor(abs(x/y))*signum(x/y)