Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a String to a BigInteger?

I'm trying to read some really big numbers from standard input and add them together.

However, to add to BigInteger, I need to use BigInteger.valueOf(long);:

private BigInteger sum = BigInteger.valueOf(0);  private void sum(String newNumber) {     // BigInteger is immutable, reassign the variable:     sum = sum.add(BigInteger.valueOf(Long.parseLong(newNumber))); } 

That works fine, but as the BigInteger.valueOf() only takes a long, I cannot add numbers greater than long's max value (9223372036854775807).

Whenever I try to add 9223372036854775808 or more, I get a NumberFormatException (which is completely expected).

Is there something like BigInteger.parseBigInteger(String)?

like image 462
Twinone Avatar asked Mar 30 '13 10:03

Twinone


People also ask

How do I convert BigDecimal to BigInteger?

toBigInteger() converts this BigDecimal to a BigInteger. This conversion is analogous to the narrowing primitive conversion from double to long. Any fractional part of this BigDecimal will be discarded. This conversion can lose information about the precision of the BigDecimal value.

How do I get BigInteger value?

BigInteger valueOf() Method in Java we can call this function by BigInteger. valueOf(long value) code. Parameter: This method accepts a single parameter value which is the value of the BigInteger to be created. Return Value: This method returns the BigInteger whose value is equal to value of long passed as parameter.


1 Answers

Using the constructor

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

Javadoc

like image 167
Uku Loskit Avatar answered Sep 18 '22 08:09

Uku Loskit