newbie: double to long conversion does not lose precision
Andrew Haley
aph at redhat.com
Sat Apr 26 14:51:56 UTC 2014
On 04/26/2014 02:48 PM, Andy Nuss wrote:
> 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.
The nearest double to Long.MAX_VALUE is 0x1.0p63.
Converting it back, 0x1.0p63 can't be represented as a long, so:
5.1.3. Narrowing Primitive Conversion
http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3
The value must be too large (a positive value of large magnitude or
positive infinity), and the result of the first step is the largest
representable value of type int or long.
HTH,
Andrew.
More information about the hotspot-compiler-dev
mailing list