It's because of rounding.
1 can be represented exactly as a double or a float so the first 4 comparisons work as expected.
1.1 == 1.1
compares a double to itself and works as expected.
1.1d == 1.1
is exactly the same as above (the d
is implied in 1.1
).
The last two comparisons compare 1.1 the double to 1.1 the float. Except that 1.1
is not exactly representable as a float (resp. double) so it gets rounded to the closest float (resp. double) - but double has a "higher resolution" so they don't get rounded similarly.
To see the exact values:
System.out.println(new BigDecimal(1.1f)); //1.10000002384185791015625
System.out.println(new BigDecimal(1.1d)); //1.100000000000000088817841970012523233890533447265625
As suggested by @yshavit in the comments, when you compare a double to a float, the float gets converted to a double (due to numeric promotion), so you are really comparing two doubles:
System.out.println(new BigDecimal((double) 1.1f)); //1.10000002384185791015625
System.out.println(new BigDecimal(1.1d)); //1.100000000000000088817841970012523233890533447265625