newbie: double to long conversion does not lose precision

Andy Nuss andrew_nuss at yahoo.com
Sat Apr 26 13:48:29 UTC 2014


Hi,

I wanted to do a function that strips the precision of json integral values if too big to hold all their decimal digits in the same way as javascript 64-bit floating point numbers lose precision if passed as 64-bit positive numbers that use all their bits.

So I wrote a function:

public static long double2long (double d)
{
    return (long)d;
}

With the idea that I would take any 64 bit long value converted from a string, and pass it thru this function to remove precision in the same way as javascript does.  However, when I tried running the code:

public static void main (String[] args)
{
    long v1 = Long.MAX_VALUE;
    long v2 = double2long(v1);
    System.out.println(v1);
    System.out.println(v2);
}

I got in the debugger and in stdout that v2 was still the same as v1.  Am I missing something or is hotspot doing something really tricky?  Or do I not understand the IEEE format of a double?  How does hotspot get all the bits but the sign bit set to 1 in v2 above?  By the way this was the latest JDK 7.

Andy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/hotspot-compiler-dev/attachments/20140426/f285713e/attachment-0001.html>


More information about the hotspot-compiler-dev mailing list