-1

I was working through debugging a program of mine where certain doubles and floats were not equal to each other. I have looked for answers previous to posting this on here as to why this would happen but could not find much relevant information. For example:

System.out.println(4.4f == 4.4); 

This prints false while,

System.out.println(4.5f == 4.5);

Prints true.

Could someone shed some light on why this is the case in JAVA?

Matt Jones
  • 511
  • 3
  • 12
  • 2
    This is not the case with Java. This is the case with floating point numbers. – DwB Oct 29 '14 at 18:46
  • 1
    That question is asked twice every week, in a form or another. Hint: there are an infinity of decimal values, but only 2^32 float values, and 2^64 double values. – JB Nizet Oct 29 '14 at 18:47

1 Answers1

5

When you write 4.4f, that results in the closest value representable as a float to the true value 4.4.

When you write 4.4, that results in the closest value representable as a double to the value 4.4.

When you write 4.4f == 4.4, that tests if the closest value representable as a float is still the closest value representable as a double to 4.4, which is false; double has more precision, and neither float nor double can represent 4.4 exactly.

Both float and double can represent 4.5 exactly, however; since they're using binary fractions, and 4.5 is an exact binary fraction, that works fine.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413