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,470
  • 10
  • 58
  • 82
sriram
  • 7,990
  • 19
  • 58
  • 80
  • 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,322
  • 3
  • 34
  • 41
4

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

Here is javadoc for BigInteger.

kosa
  • 64,776
  • 13
  • 121
  • 163
3

you might use BigInteger rather than Long.

 BigInteger number = new BigInteger(longString);

Java BigInteger example

Ami
  • 4,191
  • 6
  • 37
  • 70
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,146
  • 12
  • 71
  • 124