30

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.

user2773145
  • 381
  • 2
  • 4
  • 6
  • There is very few cases where you need longer integer types. Cryptography is one, but I don't suggest you write this yourself. Even BigDecimal only uses these selectively in Java 7. – Peter Lawrey Feb 12 '14 at 11:00

4 Answers4

30

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.

kai
  • 6,702
  • 22
  • 38
2

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

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • 8
    Strictly, this is incorrect. There are other ways he could do it ... so "must" is an over-reach. – Stephen C Feb 12 '14 at 10:27
  • @StephenC It would be helpful had you given a solution rather than what you posted. – NinjaElvis Nov 26 '19 at 12:20
  • 2
    @NinjaElvis - Why would it have been helpful? There were already 4 correct solutions. What would be the point of posting a duplicate? For a question that was a duplicate in the first place? I was simply pointing out that Kevin was incorrect in asserting that BigInteger is the only way. – Stephen C Nov 26 '19 at 12:40
2

You can use a BigInteger type.

PaolaG
  • 814
  • 1
  • 11
  • 27
-1

Please consider the Java API: http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html

Smutje
  • 17,733
  • 4
  • 24
  • 41