programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

Conversions

Greenhorn
Posts: 27
• Number of slices to send:
Optional 'thank-you' note:
Hello Everybody I have these 2 code segments which produce different results. Can anyone explain why?

On the other hand in this example

I am confused as why in first case the two integers are equal and not in the second case.

Author & Gold Digger
Posts: 7617
6
• Number of slices to send:
Optional 'thank-you' note:
as you know, int is 32-bits long and so is float. But the difference is that float has to keep decimal informations in these 32 bits, which means the maximum value of a float is less than the possible max value of an int.
See for yourself

Output:
2147483647 // == 2147483647
2.14748365E9 // == 2147483650
3.4028235E38 // == 340282350...
As you see, the conversion of int max value to float is not without risk of losing some precision, whereas the max value of a float is far less than the max value of an int...
In other words, when converting an int to a float back and forth, the bit pattern does not change, it's just that a float interprets some bits in a different way that an int does, i.e. the couple last bits in a float are for the exponent...
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
[This message has been edited by Valentin Crettaz (edited November 13, 2001).]

vinay jain
Greenhorn
Posts: 27
• Number of slices to send:
Optional 'thank-you' note:
Thanks for the explanation, that explains the first code very clearly but what about the second code, in that the value 123456789 is much less then Float.MAX_VALUE, why would that produce the difference. Also How would I find the max Integer value which can be converted to float without loosing some value in conversion?
Thanks
Vinay

Ranch Hand
Posts: 139
• Number of slices to send:
Optional 'thank-you' note:
Try this code:

The output is:
2.14748365E9==>2147483647
2.14748352E9==>2147483583
This tells us that when integers larger than 2147483583
are casted to float, they are stored the same way (as if they
were Integer.MAX_VALUE). When they are casted back to integer,
they all become Integer.MAX_VALUE.