Java: Wrong results for division?
When dividing two integers, Java uses integer division. In integer division, the result is truncated (fractional part thrown away) and not rounded to the closest integer. For example: 99 / 10 == 9
.
To get actual floating-point result
Cast the numerator (or denominator) to double
:
double r = (double) i / j; // r == 1.66666…
Rounded result
Cast numerator as above, and use Math.round
:
int r = (int) Math.round((double) i / j);
Why does the above work?
(double) i / j
is parsed as ((double) i) / j
. If one of the operands is a double
, the other operand is promoted to a double
as well. Then floating-point division is used, and the result is a floating-point value.
Comments
Be the first to comment!