Converting Long to Float: Values not Matching

Z

Z

Hi,

Small test program:

public class ClassCast {

public static void main(String[] args)
{
Long lval = new Long("3250051236");
System.out.println(lval);
Float fval = new Float(lval.floatValue());
System.out.println(fval);
}
}

I am getting:

3250051236
3.25005133E9

I tried with multiple numbers but still the values are not equal. What
am I missing?

Thanks,
 
M

Mark Space

Z said:
Hi,

Small test program:

public class ClassCast {

public static void main(String[] args)
{
Long lval = new Long("3250051236");
System.out.println(lval);
Float fval = new Float(lval.floatValue());
System.out.println(fval);
}
}

I am getting:

3250051236
3.25005133E9

I tried with multiple numbers but still the values are not equal. What
am I missing?

Thanks,

Well, let's see. long have about 64 bits of precision, floats have
about, what, 22? Then there's the whole thing about accuracy of floats
in general.

Google for "floating point accuracy" or something like this, should have
been a basic part of your education.
 
J

Joshua Cranmer

Z said:
I am getting:

3250051236
3.25005133E9

I tried with multiple numbers but still the values are not equal. What
am I missing?

Thanks,

Floats have limited precision. Your number is larger than the number of
the precision.

Internally, numbers are represented as a number (the mantissa)
multiplied by some power of 2; your number cannot be exactly represented
to the precision that the mantissa has, so it lops off a few bits at the
end, giving you a moderately close but not exact approximation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top