Search code examples
javafloating-accuracy

Floating point Weird Phenomenon in Java


Possible Duplicate:
Strange floating-point behaviour in a Java program

I came across this weird phenomenon in Java. Try this statement in a Java program:

System.out.print(4.0-3.1);

The output will be 0.8999999

Why does this happen? And how can it be changed?


Solution

  • This is a typical floating point result runded.

    You get different results from Float and Double :

    System.out.println(4.0f-3.1f);
    System.out.println(4.0d-3.1d);
    

    Output:

    0.9000001
    0.8999999999999999
    

    This is because 0.1 cannot be represented evenly in base 2, and cause a loss of precision. For example :

    System.out.println(2.0f-1.9f);
    System.out.println(2.0d-1.9d);
    

    Should both return 0.1 but in fact will output :

    0.100000024
    0.10000000000000009