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 r = (double) i / j; // r == 1.66666…
Cast numerator as above, and use
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.