1
class MagicWithOperators{
    public static void main(String[] args) {
        float  f = 10.2F; 
        double d = 10.2; 
        System.out.println(f==d);
    }
}

Output: false.

why 10.2f==10.2 is false but 10.0f==10.0 is true?

Pshemo
  • 122,468
  • 25
  • 185
  • 269

1 Answers1

2

The reason is that the value 10.2 cannot be represented exactly, using either float or double representations. Both are different approximations to 10.2, which are mathematically not equal.

The reason that it's true for 10.0f and 10.0 is that 10 can be represented exactly in both float and double representations.

Here are the hexadecimal representations of all the numbers above.

41233333          // 10.2f (float, inexact)
4024666666666666  // 10.2  (double, inexact)
4024666660000000  // 10.2f (widened to double, inexact)

41200000          // 10.0f (float, exact)
4024000000000000  // 10.0  (double, exact)
4024000000000000  // 10.0f (widened to double, exact)

The conversions are done with Integer.toHexString(Float.floatToIntBits()) and Long.toHexString(Double.doubleToLongBits).

rgettman
  • 176,041
  • 30
  • 275
  • 357