# long and float conversion

• 01-06-2011, 11:07 AM
jomypgeorge
long and float conversion
i am confused with conversion between long and float.
long is 64 bit , but float only 32 bit, then how can we assign a long variable to float variable without error?

how i got this code compiled?

class LongToFloat
{
long a = 1234567890;
float b = a;
}
• 01-06-2011, 02:48 PM
Tolls
Because a float is a floating point so rounds it off.
Try it with 12345678912345L and print out both a and b.
• 01-06-2011, 03:30 PM
JosAH
Quote:

Originally Posted by jomypgeorge
i am confused with conversion between long and float.
long is 64 bit , but float only 32 bit, then how can we assign a long variable to float variable without error?

how i got this code compiled?

class LongToFloat
{
long a = 1234567890;
float b = a;
}

It is a bit strange indeed but the conversion from long to float is called a 'widening conversion' because longs can store (integral) numbers up to 1E18 while floating point numbers can be as large as 1E38; you do lose accuracy though because floats can only store 7 digits while a long can store up to 18 digits. But still you can implicitly cast longs to floats as you already have noticed.

kind regards,

Jos
• 01-06-2011, 04:59 PM
neilcoffey
Other cast problems...
Just to add a couple of other examples of problematic casts that you should be aware of. Even casting between floating point and integer types of the same number of bits is problematic. Try this:

Code:

```                  long l = 0x123456712345678L;                   double d = l;                   long lAgain = (long) d;                   System.out.println(Long.toHexString(lAgain));```
Another example of a cast to a type with a larger number of bits but where the cast doesn't necessarily lead to the same value is converting from a byte to a char: a byte is signed, but char is unsigned. So converting (byte) 255 to a char will actually give you a char with a value of 65535...

It's arguable whether casts from integer to floating point types should have been allowed to be unchecked.
• 01-07-2011, 07:05 AM
jomypgeorge