This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
Hi Suresh, Welcome to the world or IEEE 754. the primitive type double is not the same as float in this world. Let the JLS Spec illuminate you (Section 5.1.2):
Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode.
Interesting. I would have expected "unequal unequal equal equal equal". When the Long.MAX_VALUE is converted to double, some precision is lost. When the Long.MAX_VALUE is converted to float, even more bits of precision are lost. When the float version is converted to double for the comparison, is the extra precision just accidently coming out equal?
With this line: System.out.println("d= " + d + "\n" + "f= " + f + "\n" + "(double)f: " + (double)f); we can see the following output: d= 9.223372036854776E18 f= 9.223372E18 (double)f: 9.223372036854776E18 equal d= 2.147483647E9 f= 2.14748365E9 (double)f: 2.147483648E9 unequal d= 65535.0 f= 65535.0 (double)f: 65535.0 equal d= 32767.0 f= 32767.0 (double)f: 32767.0 equal d= 127.0 f= 127.0 (double)f: 127.0 equal Also if we add: compare(5555555555L, 5555555555L); the output: d= 5.555555555E9 f= 5.5555553E9 (double)f: 5.555555328E9 unequal I would say that comparing floating point numbers with == is very risky. I think it's better to establish the precission that is going to be meaningfull for our comparision before doing the actual comparision. Maybe rounding... Please correct or confirm.