Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Large Numbers in Java

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?

like image 849
Petey B Avatar asked May 11 '09 20:05

Petey B


People also ask

How do you use large numbers in Java?

Use the static valueOf method to turn an ordinary number into a big number: BigInteger a = BigInteger. valueOf(100);

What is the largest number format in Java?

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.

What is bigger than integer in Java?

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.


1 Answers

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); 
like image 87
Fabio Vinicius Binder Avatar answered Oct 17 '22 04:10

Fabio Vinicius Binder