Search code examples
javaprimitive

surprising double comparison


I have messed with code execution result.

code:

System.out.println(0.2==0.1+0.1);
System.out.println(0.3==0.1+0.1+0.1);

output:

true
false

I know that 0.2 and 0.3 cannot transform to binary correct.

Why do I see different results?

UPDATE:

Can I predict result in similar issues without compiler?


Solution

  • PHP gave this:

    <?php
    
    printf("%0.20f\n", 0.1+0.1);
    printf("%0.20f\n", 0.1+0.1+0.1);
    
    ?>
    0.20000000000000001110
    0.30000000000000004441
    

    and

    <?php
      echo 0.2==0.1+0.1?"true\n":"false\n";
      echo 0.3==0.1+0.1+0.1?"true\n":"false\n";
    ?>
    true
    false
    

    The reaseon for the first to be "true":

    <?php
       printf("%0.20f\n", 0.1+0.1);
       printf("%0.20f\n", 0.1+0.1+0.1);
       echo "\n";
       printf("%0.20f\n", 0.2);
       printf("%0.20f\n", 0.3);
    ?>
    

    Output

    0.20000000000000001110
    0.30000000000000004441
    
    0.20000000000000001110
    0.29999999999999998890