2

Hi I have a big string like this :

"999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"

I wish to convert this string to long. But I failed. I did:

Long.parseLong(longString);

But I'm getting an error:

java.lang.NumberFormatException: For input string: "99999999.......

Are there any way to avoid this?

Vikdor
  • 23,934
  • 10
  • 61
  • 84
sriram
  • 8,562
  • 19
  • 63
  • 82
  • 1
    Note that using BigInteger as suggested below will remove the ability to use operators (+, -, *, etc). Just be wary of that... you'll have to use a = a.add(b). – Ryan Amos Oct 19 '12 at 04:04
  • 1
    [There are limits to the types of numbers that primitive values can represent.](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) – Makoto Oct 19 '12 at 04:05
  • http://stackoverflow.com/questions/5318068/very-large-numbers-in-java-without-using-java-math-biginteger – Chin Oct 19 '12 at 04:06

4 Answers4

9

Use BigInteger class like this:

 BigInteger number = new BigInteger(longString);
higuaro
  • 15,730
  • 4
  • 36
  • 43
4

You need to use BigInteger. Long may not accommodate that big number.

Here is javadoc for BigInteger.

kosa
  • 65,990
  • 13
  • 130
  • 167
3

you might use BigInteger rather than Long.

 BigInteger number = new BigInteger(longString);

Java BigInteger example

Ami
  • 4,241
  • 6
  • 41
  • 75
3

long: Reference

use 8-byte to store values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

As mention before answer, use BigInteger.

Zaw Than oo
  • 9,651
  • 13
  • 83
  • 131