java.lang.NumberFormatException用于大数字

时间:2012-10-24 07:58:58

标签: java

在下面的代码中,当输入大数字~1000000000时,我得到一个java.lang.NumberFormatException。错误发生在倒数第二行 - \

int integer = Integer.parseInt(split[0]);

它应该在理论上起作用,因为Integer类型支持直到2 ^ 32-1但它不

Scanner user_input = new Scanner(System.in);
//accept user input and convert into double
String s = user_input.next();
double number = Double.parseDouble(s);
System.out.println(number);

String answer = "";

//Split the entered number into Integer and Decimal parts
String split[] = Double.toString(number).split("\\.");
int integer = Integer.parseInt(split[0]);
int decimal = Integer.parseInt(split[1]);

4 个答案:

答案 0 :(得分:1)

问题可能是因为一个大型双重表示将采用科学记数法:

1.0E9

这意味着拆分失败,请尝试打印出要解析的字符串的值。

当您在double上调用toString时,使用的格式可能会有所不同,请尝试使用DecimalFormat代替:

new java.text.DecimalFormat("0.00000000").format(number)

答案 1 :(得分:0)

根据Javadoc,当“字符串无法解析为整数”时会发生这种情况。除其他原因外,如果值超过Integer.MAX_VALUEInteger.MIN_VALUE,则会出现这种情况。

所以大于20亿或小于负20亿的东西(确切地说是2 ^ 31-1,并且-2 ^ 31)。你的例子,-1,000,000,000(添加逗号)应该可以工作。

答案 2 :(得分:0)

问题是大数字表示为1.E9或类似。因此,当您执行拆分以获得integer值时,您将获得1,而对于decimal部分,您将获得E9这不是数字。

答案 3 :(得分:0)

当然数字1000000000是有效的,但我怀疑字符〜导致NumberFormatException。你应该小心使用这段代码,因为像这样的数字1.34184E24是java中的有效Double,但使用Integer.parseInt解析小数分割也会导致NumberFormatException,因为有一个E.