Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store a number that is longer than type long in Java [duplicate]

Tags:

java

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.

like image 704
user2773145 Avatar asked Feb 12 '14 10:02

user2773145


People also ask

How do you store numbers bigger than long?

You must use BigInteger to store values that exceed the max value of long.

How many digits can long store Java?

You can store this in a long . A long can store a value from -9223372036854775808 to 9223372036854775807 . To be clear, at least 18 digits.

Which is bigger double or long Java?

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.


3 Answers

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.

like image 147
kai Avatar answered Oct 19 '22 03:10

kai


You must use BigInteger to store values that exceed the max value of long.

like image 43
Kevin Bowersox Avatar answered Oct 19 '22 05:10

Kevin Bowersox


You can use a BigInteger type.

like image 2
PaolaG Avatar answered Oct 19 '22 05:10

PaolaG