How can I store a number that is longer than the long type (MAX: 9223372036854775807) in Java?
For example the number 9223372036854775820.
Thanks in advance.
You must use BigInteger to store values that exceed the max value of long.
You can store this in a long . A long can store a value from -9223372036854775808 to 9223372036854775807 . To be clear, at least 18 digits.
If you are storing integers, use Long . Your statement that "Advantage of Using Double is that it gives a more wider range for storing Whole Numbers" is incorrect. Both are 64 bits long, but double has to use some bits for the exponent, leaving fewer bits to represent the magnitude.
Use BigInteger
if you work with a long and use BigDecimal
if you work with floatingpoint numbers. The BigInteger
can be as big as you want, till there is not enough RAM.
Example:
BigInteger bd = new BigInteger("922337203685477582012312321");
System.out.println(bd.multiply(new BigInteger("15")));
System.out.println(bd);
Output:
13835058055282163730184684815
922337203685477582012312321
But have to use the BigInteger
methods to do calculations and in the example you see that BigInteger
is immutable.
You must use BigInteger to store values that exceed the max value of long.
You can use a BigInteger type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With