permaculture playing cards
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Conversion of long to float Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Conversion of long to float" Watch "Conversion of long to float" New topic

Conversion of long to float


Joined: Nov 03, 2000
Posts: 4
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.
Udayan Naik
Ranch Hand

Joined: Oct 18, 2000
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 !!

Udayan Naik<BR>Sun Certified Programmer for the Java 2 Platform
Sapna Mathur

Joined: Nov 06, 2000
Posts: 8

But isnt long to float a narrowing conversion?
Oliver Grass
Ranch Hand

Joined: Nov 02, 2000
Posts: 65
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

Joined: Sep 07, 2000
Posts: 16
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.
shailesh sonavadekar
Ranch Hand

Joined: Oct 12, 2000
Posts: 1874
gayathri_jag & SathishVJ , as part of naming policy of the site user has to register with proper first name & last name. Gayatri & Satish , I request you to register yourself with proper last name & help javaranch to maintain decorum.
I agree. Here's the link:
subject: Conversion of long to float
It's not a secret anymore!