# Thread: long and float conversion

1. Member
Join Date
May 2010
Posts
90
Rep Power
0

## 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;
}

2. Moderator
Join Date
Apr 2009
Posts
13,215
Rep Power
23
Because a float is a floating point so rounds it off.
Try it with 12345678912345L and print out both a and b.

3. 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

4. Senior Member
Join Date
Nov 2008
Posts
286
Rep Power
9

## 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:

Java 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.
Last edited by neilcoffey; 01-06-2011 at 05:01 PM. Reason: Extra point added

5. Member
Join Date
May 2010
Posts
90
Rep Power
0