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?
Use the static valueOf method to turn an ordinary number into a big number: BigInteger a = BigInteger. valueOf(100);
The largest integer number that a long type can represent is 9223372036854775807. If we deal with even larger numbers, we have to use the java. math. BigInteger class.
byte 1 byte -128 to 127. short 2 bytes -32,768 to 32,767. int 4 bytes -2,147,483,648 to 2,147,483,647. long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,80.
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);
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