Converting Long to Float: Values not Matching

Discussion in 'Java' started by Z, Sep 12, 2008.

  1. Z

    Z Guest

    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,
    Z, Sep 12, 2008
    #1
    1. Advertising

  2. Z

    Mark Space Guest

    Z wrote:
    > 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.
    Mark Space, Sep 12, 2008
    #2
    1. Advertising

  3. Z wrote:
    > 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.
    --
    Beware of bugs in the above code; I have only proved it correct, not
    tried it. -- Donald E. Knuth
    Joshua Cranmer, Sep 12, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. bd
    Replies:
    0
    Views:
    621
  2. mathieu
    Replies:
    9
    Views:
    738
    James Kanze
    Sep 15, 2007
  3. Oliver Graeser
    Replies:
    10
    Views:
    581
    Oliver Graeser
    Sep 26, 2008
  4. Carsten Fuchs
    Replies:
    45
    Views:
    1,535
    James Kanze
    Oct 8, 2009
  5. Dipesh Batheja
    Replies:
    1
    Views:
    572
    Bernard Kenik
    Nov 16, 2006
Loading...

Share This Page