-1
double foo = 3;
double bar = 2.1;

System.out.println(foo - bar + "");

Output:

0.8999999999999999

Why? Is this some Java joke, which is not understandable for mere mortals?

Lajos Arpad
  • 53,986
  • 28
  • 88
  • 159

1 Answers1

4

It isn't a joke. It is floating-point precision error problem. The main gist of this problem is that floating points are represented in base 2 rather than 10, and that the precision of doubles is not arbitrary.

If you want precision, you can use BigDecimal class:

jh314
  • 25,902
  • 15
  • 60
  • 80