如何解析字符串中的大整数?

时间:2013-05-24 08:03:12

标签: java

我有这样的方法:

Integer.parseInt(myInt)

这个整数不会变长,我得到以下异常:

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

我该怎么做才能避免这个错误并仍然保持运行的功能?

我尝试使用BigInteger,但没有parse方法,或者我没有找到它。

4 个答案:

答案 0 :(得分:23)

像这样使用它。

 BigInteger number = new BigInteger(myInt);

答案 1 :(得分:7)

我的解决方案:

String sLong = "4000123012";
long yourLong = Long.parseLong(sLong);
System.out.println("Long : "+yourLong);

OutPut:

Long : 4000123012

答案 2 :(得分:2)

你也可以使用Long.parse作为整数:

Long.parseLong(myInt)

当然会返回long

答案 3 :(得分:1)

Java Integer最大值为2147483647(table of limits)。

您可以通过Long.parseLong(String s)将字符串转换为Long并通过将long传递给BigInteger.valueOf(long l)来获取BigInteger

String s = "4000123012";
long l = Long.parseLong(s);
BigInteger bi = BigInteger(l);

编辑: 在将一种类型解析为另一种类型时,您将始终尝试捕获异常,并在这种情况下采取行动,例如设置一些默认值。

更好,Alpesh Prajapati建议将String传递给构造函数:

BigInteger number = new BigInteger(myInt);