-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
  • 64,414
  • 37
  • 100
  • 175

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
  • 27,144
  • 16
  • 62
  • 82