Java: Wrong results for division?

When dividing two integers, Java uses integer division. In integer division, the result is also an integer. The result is truncated (fractional part thrown away) and not rounded to the closest integer.

To get actual floating point result

Cast the numerator (or denominator) to double:

double r = (double) i / j;

To get rounded result

Cast as above, and use Math.round:

long r = Math.round((double) i / j);


Be the first to comment!