In Java, double
values are IEEE floating point numbers. Unless they are a power of 2 (or sums of powers of 2, e.g. 1/8 + 1/4 = 3/8), they cannot be represented exactly, even if they have high precision. Some floating point operations will compound the round-off error present in these floating point numbers. In cases you’ve described above, the floating-point errors have become significant enough to show up in the output.
It doesn’t matter what the source of the number is, whether it’s parsing a string from a JTextField
or specifying a double
literal — the problem is inherit in floating-point representation.
Workarounds:
-
If you know you’ll only have so many decimal points, then use integer
arithmetic, then convert to a decimal:(double) (51 + 1) / 10 (double) (48 - 4) / 10
-
Use BigDecimal
-
If you must use
double
, you can cut down on floating-point errors
with the Kahan Summation Algorithm.