From JLS 5.1.2: int big = 1234567890; float f = big; System.out.println(i - (int)f); is not 0, as the float values are not precise for nine significant digits. Going by the same, I was not expecting to get a 0 when I used, Integer.MAX_VALUE for 'big'. Why is that 0 ?
Hi Rekha, You might have missed the sentence before the example in the JLS section 5.1.2. I have bolded the important word in the sentence.
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
I don't see where it says that the conversion will always fail. It only says that the conversion may not work as programmers might expect it to under all conditions. Regards, Manfred. [This message has been edited by Manfred Leonhardt (edited December 21, 2001).]
Hello Rekha I think what you are asking is why the following code prints -46 but 0
The output is " -46 2.14748365E9 2147483647 0 " You can see how f=big looses precission : 2.147448365E9 ends in 5 instead of 47. The subtlety is that narrowing from floating point to integer produces Integer.MAX_VALUE if the floating point number is an infinity or too large for being represented in the integer format. So (int)f prints 2147483647. Read JLS 5.1.3
*... * The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.