Precision error with floats in Java

The problem is not with Java but with the good standard float's (http://en.wikipedia.org/wiki/IEEE_floating-point_standard).

You can either:

  • use Double and have a bit more precision (but not perfect of course, it also has limited precision)

  • use a arbitrary-precision-library

  • use numerically stable algorithms and truncate/round digits of which you are not sure they are correct (you can calculate numeric precision of operations)


If you really care about precision, you should use BigDecimal

https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html


When you print the result of a double operation you need to use appropriate rounding.

System.out.printf("%.2f%n", 1.89 * 792);

prints

1496.88

If you want to round the result to a precision, you can use rounding.

double d = 1.89 * 792;
d = Math.round(d * 100) / 100.0;
System.out.println(d);

prints

1496.88

However if you see below, this prints as expected, as there is a small amount of implied rounding.


It worth nothing that (double) 1.89 is not exactly 1.89 It is a close approximation.

new BigDecimal(double) converts the exact value of double without any implied rounding. It can be useful in finding the exact value of a double.

System.out.println(new BigDecimal(1.89));
System.out.println(new BigDecimal(1496.88));

prints

1.8899999999999999023003738329862244427204132080078125
1496.8800000000001091393642127513885498046875