开发者

How can I avoid a NumberFormatException in Java?

开发者 https://www.devze.com 2023-01-25 12:28 出处:网络
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.

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.

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. the only problem is the double value. it is something like 5837848.3748980 but the valueOf method always throws the exception here. 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:

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


This is a starting point for using DecimalFormat to convert strings to numbers. Also, if you are dealing with money and currencies, you should consider using BigDecimal instead of double.


You are using Integer.parseInt on a number with a decimal point - that is not a valid integer - visible in your stack trace

0

精彩评论

暂无评论...
验证码 换一张
取 消