[英]How can I avoid a NumberFormatException in Java?
i searched, i found, but it all didn't work. 我找到了,但是一切都没有用。 my problem is that the
NumberFormatException
is thrown while I want to cast from String
to double
. 我的问题是,当我想从
String
为double
抛出NumberFormatException
。
The string array atomized contains many strings and I tried to make an output before to make them visible so I could be sure there is data. 字符串数组atomized包含许多字符串,我尝试先输出,使它们可见,所以我可以肯定有数据。 the only problem is the double value.
唯一的问题是双重值。 it is something like 5837848.3748980 but the valueOf method always throws the exception here.
它类似于5837848.3748980但是valueOf方法总是抛出异常。 I have no idea why.
我不知道为什么。
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());
}
Exception output: 异常输出:
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)
It works fine here. 它在这里工作正常。 So I'd assume your system locale has
,
rather than .
所以我假设您的系统区域设置有
,
而不是.
for decimal separator. 用于小数分隔符。 To avoid these things you can use
DecimalFormat
: 要避免这些事情,您可以使用
DecimalFormat
:
new DecimalFormat().parse("5837848.3748980");
Judging by the name of your variable - account - I assume you are dealing with money. 从你的变量的名称判断 - 账户 - 我假设你正在处理钱。 You must never use floating point types to represent money.
您绝不能使用浮点类型来代表金钱。 Use
BigDecimal
, or possibly int
使用
BigDecimal
,或者可能是int
This is a starting point for using DecimalFormat to convert strings to numbers. 这是使用DecimalFormat将字符串转换为数字的起点。 Also, if you are dealing with money and currencies, you should consider using BigDecimal instead of double.
此外,如果您正在处理货币和货币,您应该考虑使用BigDecimal而不是double。
您在一个带小数点的数字上使用Integer.parseInt - 这不是一个有效的整数 - 在堆栈跟踪中可见
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.