简体   繁体   English

解析数字时出现NumberFormatException

[英]NumberFormatException while parsing a Number

String str="123456.7855456677";
ParsePosition parsePosition = new ParsePosition(0);
NumberFormat numberFormat=new DecimalFormat();
Number number=numberFormat.parse(str, parsePosition);

if(parsePosition.getIndex()!=str.length())
{
    throw new IllegalArgumentException();
}

numberFormat.setMaximumFractionDigits(2);
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
double value=Double.parseDouble(numberFormat.format(number));
System.out.println(value);

The value of the String type variable str in this segment of code can be any dynamic value, assuming a user is free to input any string. 假设用户可以自由输入任何字符串,则此代码段中String类型变量str值可以是任何动态值。

The Double.parseDouble() method on the second last line causes the java.lang.NumberFormatException to be thrown. 最后一行Double.parseDouble()方法导致抛出java.lang.NumberFormatException

Removing the line numberFormat.setMaximumFractionDigits(2); 删除行号numberFormat.setMaximumFractionDigits(2); and setting a RegEx to the overloaded constructor of the DecimalFormat class instead as usual like, 并像往常一样将RegEx设置为DecimalFormat类的重载构造函数,

NumberFormat numberFormat=new DecimalFormat("#.##");

suppresses the exception. 抑制异常。

So, why doesn't it work otherwise? 那么,为什么它不起作用呢?

如果你可以调试代码然后检查这行numberFormat.format(number)放置它给出一个包含可能成为异常原因的逗号的数字,检查这个123,456.79并且这个逗号不应该在那里...希望这会有帮助。

Exception in thread "main" java.lang.NumberFormatException: For input string: "123,456.79"在双Exception in thread "main" java.lang.NumberFormatException: For input string: "123,456.79"数字的字符串表示形式内不能有逗号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM