Search code examples
javafractions

Weird Java fraction behavior


I have seen a very weird behaviour in Java's double variable, as I'm trying to simply add small fractions to a double and I see a completely bizarre results.

double test = 0;
test += 0.71;
test += 0.2;

Now I'd expect the result to be:

test = 0.91

Right? Wrong!

In reality, this is the number I get in my test double:

test = 0.9099999999999999

Now while this is very close, it's a very bizarre fraction loss, and in the long run it causes serious bugs in my program.

With a float I've gotten even a weirder result.

Any help would be greatly appreciated.

Thanks


Solution

  • That's the magic of binary encoding of floating point values (look for IEEE754 : http://en.wikipedia.org/wiki/IEEE_754-2008 ). If you want to be sure to never have this kind of things, you're maybe looking for BigDecimal :

    http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html

    Basic rules :

    • don't use equality tests when dealing with floating point numbers (you must test gaps)
    • round numbers you're displaying (usually using DecimalFormat)
    • don't use floating point numbers for financial applications
    • the float is generally the way to go for scientific or industrial operations, as long as you understand IEEE754