如何在Java中避免NumberFormatException?

And*_*dre 4 java casting exception

我找到了,但是一切都没有用.我的问题是,NumberFormatException是当我想从投抛出Stringdouble.

字符串数组atomized包含许多字符串,我尝试先输出,使它们可见,所以我可以肯定有数据.唯一的问题是双重值.它类似于5837848.3748980但是valueOf方法总是抛出异常.我不知道为什么.

try
{
 int key = Integer.valueOf(atomized[0]);

 double value = Double.valueOf(atomized[1].trim());

 int role = Integer.valueOf(atomized[2]);

 Double newAccountState = this.bankKonto.charge(key, value, role);
 System.out.println("NEW Account State "+newAccountState);
 this.answerClient(newAccountState.toString());
}
catch (NumberFormatException e)
{
 System.out.println(e.getClass().toString()+" "+e.getMessage());
} 
Run Code Online (Sandbox Code Playgroud)

异常输出:

java.lang.NumberFormatException: For input string: "109037.0"
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.valueOf(Unknown Source)
        at vsys.ue02.server.Bank.computeData(Bank.java:122)
        at vsys.ue02.server.Bank.run(Bank.java:160)
Run Code Online (Sandbox Code Playgroud)

Boz*_*zho 11

它在这里工作正常.所以我假设您的系统区域设置,而不是.小数分隔符.要避免这些事情,您可以使用DecimalFormat:

new DecimalFormat().parse("5837848.3748980");
Run Code Online (Sandbox Code Playgroud)

从你的变量的名称判断 - 账户 - 我假设你正在处理钱.您绝不能使用浮点类型来代表金钱.使用BigDecimal,或可能int