如何在Java中将非常大的String转换为数字

时间:2012-10-19 04:01:09

标签: java string numbers

嗨,我有一个像这样的大字符串:

  

“999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999”

我希望将此字符串转换为long。但我失败了。我做了:

Long.parseLong(longString);

但是我收到了一个错误:

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

有什么方法可以避免这种情况吗?

4 个答案:

答案 0 :(得分:6)

像这样使用BigInteger类:

 BigInteger number = new BigInteger(longString);

答案 1 :(得分:4)

您需要使用BigIntegerLong可能无法容纳这么多人。

这是BigInteger的javadoc。

答案 2 :(得分:3)

您可以使用BigInteger而不是Long。

 BigInteger number = new BigInteger(longString);

Java BigInteger example

答案 3 :(得分:2)

长: Reference

使用8字节存储-9,223,372,036,854,775,8089,223,372,036,854,775,807

的值

如前所述,请使用BigInteger

相关问题