Twinone Twinone - 3 years ago 255
Java Question

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


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
only takes a
, I cannot add numbers greater than
's max value (9223372036854775807).

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

Is there something like

Answer Source

Using the constructor

BigInteger(String val)

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download