aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Widening conversion from int to float.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Widening conversion from int to float.. " Watch "Widening conversion from int to float.. " New topic
Author

Widening conversion from int to float..

Rekha Rao
Greenhorn

Joined: Jan 23, 2001
Posts: 15
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 ?
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
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).]
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
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.


SCJP2. Please Indent your code using UBB Code
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Widening conversion from int to float..