File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes conversion from long to float Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "conversion from long to float" Watch "conversion from long to float" New topic

conversion from long to float

Suneela Joshi

Joined: Oct 19, 2003
Posts: 12
Long is 64 bytes and both int and float are 32 bytes. Why can a long
be assigned to a float without an explicit cast but an int can not?
If a long is declared as follows:
long l = 123456L;
This doesn't implicitly convert
int i = l; // Gives a compile error as expected
but doing this safely compiles and run.
float f = l;
Can someone please explain?
Vinod Venkatasubramanian

Joined: Oct 19, 2003
Posts: 13
The way floats are stored internally (in the form of exponents) gives it a larger range and hence makes it safe to cast a long to a float.
Long to int of course might lead to possible loss of info.
Inquisitive M.

Joined: Dec 20, 2002
Posts: 1
Good question. A floating point number uses essentially the binary
version of scientific notation... so it can express the very large
possible values of long variables, but with a loss of *precision*. That
is, I might convert (this example by analogy is actually using decimal
precisions) 23472166003027 into (2.34722 * 10^13) as a floating point
Whether this should be considered a widening conversion (and thus not
need a cast) is a debatable point, but the Java design team decided that
it should. On the pro side, you do get a reasonable value, even if
precision is lost (compare with, for example, converting long to int,
where a value out of range creates a practically random numeric result).
On the con side, it *is* a loss of precision, so perhaps the user should
be warned about it.
I'm always in favor of compiler checks, so I disagree with Java's choice
on this one.
If this would help, this is the data from IEEE 754 Floating Point which Java complies :
A float is 4 bytes, 32 bits,
With 6 to 7 significant digits of accuracy.
covers a range from �1.40129846432481707e-45 to �3.40282346638528860e+38,
is formed of 3 fields:
1-bit sign
8-bit base 2 exponent biased+127
23-bit fraction, lead 1 implied
e.g. 3. = 0x404000
-3. = 0xC04000
I agree. Here's the link:
subject: conversion from long to float
It's not a secret anymore!