Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the maximum safest integer of a Double in Java

Tags:

java

math

Having in mind that Java's doubles are double-precision floating-point numbers. And the maximum integer without loosing precision is 9007199254740991 or 253-1

Is there any clean way of getting this value? For instance, like a constant as in JavaScript's MAX_SAFE_INTEGER

like image 205
Gonzalo Matheu Avatar asked Jul 27 '16 00:07

Gonzalo Matheu


1 Answers

There is an internal JDK class named sun.misc.DoubleConsts which has some constants that you could use to generate the value you're looking for using the "accpetable" magic numbers of 1 and 2, but it doesn't have the number defined itself.

public static long MAX_SAFE_VALUE = 
        sun.misc.DoubleConsts.SIGNIF_BIT_MASK * 2 + 1;

// alternatively
public static long MAX_SAFE_VALUE = 
        Math.pow(2, sun.misc.DoubleConsts.SIGNIFICAND_WIDTH) - 1;

However, relying on a class in the sun.misc package is not a very "clean" approach, so I'd just create my own constant.

like image 56
bdkosher Avatar answered Sep 18 '22 08:09

bdkosher