If you are storing integers, use Long . Your claim that βThe advantage of using Double is that it provides a wider range for storing integersβ is incorrect. Both are 64 bits long, but double should use some bits for the exponent, leaving fewer bits to represent the value. You can store large numbers in double , but you will lose precision.
In other words, for numbers larger than some upper bound, you can no longer store adjacent "integers" ... given an integer value above this threshold, the "next" possible double will be more than 1 more than the previous number.
for instance
public class Test1 { public static void main(String[] args) throws Exception { long long1 = Long.MAX_VALUE - 100L; double dbl1 = long1; long long2 = long1+1; double dbl2 = dbl1+1; double dbl3 = dbl2+Math.ulp(dbl2); System.out.printf("%d %d\n%f %f %f", long1, long2, dbl1, dbl2, dbl3); } }
It is output:
9223372036854775707 9223372036854775708 9223372036854776000.000000 9223372036854776000.000000 9223372036854778000.000000
note that
- The double representation of Long.MAX_VALUE-100 makes NOT equal to the original value.
- Adding 1 to the double view of Long.MAX_VALUE-100 has no effect
- With this value, the difference between one double and the next possible double value is 2000.
Another way of saying this is that Long has an accuracy of up to 19 digits, and double has only 16-digit accuracy. A double can store numbers exceeding 16 digits, but due to truncation / rounding in the lower digits.
If you need accuracy over 19 digits, you should resort to BigInteger with the expected performance degradation.
source share