Large Numbers in Java

Petey B picture Petey B · May 11, 2009 · Viewed 217.8k times · Source

How would I go about doing calculations with extremely large numbers in Java?

I have tried long but that maxes out at 9223372036854775807, and when using an integer it does not save enough digits and therefore is not accurate enough for what I need.

Is there anyway around this?

Answer

Fabio Vinicius Binder picture Fabio Vinicius Binder · May 11, 2009

You can use the BigInteger class for integers and BigDecimal for numbers with decimal digits. Both classes are defined in java.math package.

Example:

BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);