Double subtraction precision issue

Yes it worked this way using BigDecimal operations

private static void subtractUsingBigDecimalOperation(double a, double b) {
  BigDecimal c = BigDecimal.valueOf(a).subtract(BigDecimal.valueOf(b));
  System.out.println(c);
}

enter image description here


double and float are not exactly real numbers.

There are infinite number of real numbers in any range, but only finite number of bits to represent them! for this reason, rounding errors is expected for double and floats.

The number you get is the closest number possible that can be represented by double in floating point representation.

For more details, you might want to read this article [warning: might be high-level].

You might want to use BigDecimal to get exactly a decimal number [but you will again encounter rounding errors when you try to get 1/3].


double is internally stored as a fraction in binary -- like 1/4 + 1/8 + 1/16 + ...

The value 0.005 -- or the value 1.435 -- cannot be stored as an exact fraction in binary, so double cannot store the exact value 0.005, and the subtracted value isn't quite exact.

If you care about precise decimal arithmetic, use BigDecimal.

You may also find this article useful reading.

Tags:

Double

Java