Why is 0.5==0.5f is true but 0.1==0.1f is false?

Anurag Shukla picture Anurag Shukla · Jul 11, 2015 · Viewed 9.1k times · Source

Please look at following two code:

public static void main(String... args)
{
   System.out.println(0.5==0.5f);
}

Output : true

 public static void main(String... args)
 {
   System.out.println(0.1==0.1f);
 }

Output: false

Why is it happening so?

Answer

David Pérez Cabrera picture David Pérez Cabrera · Jul 11, 2015

You are comparing two types of values: double and float. Think about the limitations of size with inexact numbers.

An example:

Exact values (decimal)

value1 -> 1/2 with 5 decimals is 0.50000
value2 -> 1/2 with 10 decimals is 0.5000000000

then

value1 == value2 -> returns true

Inexact values (decimal)

value3 -> 1/3 with 5 decimals is 0.33333
value4 -> 1/3 with 10 decimals is 0.3333333333

then

value3 == value4 -> returns false because they aren't the same.

0.1 cannot be represent exactly in binary (like 1/3 in decimal) but 0.5 can be.

The binary representation of 0.1d -> 0.000(1100)1100110011...
The binary representation of 0.5d -> 0.1