newbie: double to long conversion does not lose precision

David Chase david.r.chase at oracle.com
Sun Apr 27 03:49:10 UTC 2014


You might try declaring double2long to be strictfp, see if that makes a difference,

On 2014-04-26, at 10:51 AM, Andrew Haley <aph at redhat.com> wrote:
> On 04/26/2014 02:48 PM, Andy Nuss wrote:
>> 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.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 801 bytes
Desc: Message signed with OpenPGP using GPGMail
URL: <http://mail.openjdk.java.net/pipermail/hotspot-compiler-dev/attachments/20140426/a695c743/signature.asc>


More information about the hotspot-compiler-dev mailing list