programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Conversion of long to float

gayathri_jag
Greenhorn
Posts: 4
Hi,
Is conversion of long to float possible automatically?
since float (32) precision and long is (64) precision.
in S& H book it says that it is possible.
confused?
gayathri

Udayan Naik
Ranch Hand
Posts: 135
Yes Gayathri,the conversion from long to float is a conversion and not a cast.This is because the range of float is more than that of long.A variable of type long can represent only integral values while a float vraiable can represent integral as well as floating point values.

------------------
Come on in !! Drinks are on the house in the Big Moose Saloon !!

Sapna Mathur
Greenhorn
Posts: 8

But isnt long to float a narrowing conversion?

Oliver Grass
Ranch Hand
Posts: 65
Hi,
no, long to float isn't a narrowing conversion. It is a widening one.
On the first glance this seems strange cause float is 32-bit and long is 64-bit. BUT this has to do with the internal representation of integral and floating-point types. A long is represented as a 64-bit signed two's-complement integer. A float is represented using 32-bit IEEE 754 floating-numbers...
Sounds a little bit complex, but isn't. If you've never heard of these before, just ask, perhaps i or someone else can explain....
as always correct me if i'm wrong
Oliver

SathishVJ
Greenhorn
Posts: 16
Hi,
I don't know exactly why it works the way it does. Anyways, try out this piece of code. Apparently the JVM is approximating the the long to fit it into the float. The normal representation of floats and doubles being sign*mantissa*2^exponent, it allows the JVM to approximate (incorrectly) the long value into a certain number in the exponent.
So point is conversion is possible but is erroneous on large values.
public class test {
public static void main(String args[]){
long l = 123455432123456789l;
float f = 3.2f;
f = l;
System.out.println(f); //prints 1.23455433E17 or something similar
l = (long)f;
System.out.println(l); //prints 123455433309421568 or something similar
}
}
Hope I was able to help.
Regds
Sathish