How can I avoid a NumberFormatException in Java?

I searched, I found, but none of this worked. my problem is that a NumberFormatException thrown, and I want to throw from String to double .

The string array containing the atoms contains many strings, and I tried to draw the output earlier to make them visible so that I can be sure that there is data. the only problem is the double meaning. it's something like 5837848.3748980, but the valueOf method always throws an 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) 
+4
source share
3 answers

It works great here. Therefore, I would suggest that your locale system has,, and not . for decimal separator. To avoid these things, you can use DecimalFormat :

 new DecimalFormat().parse("5837848.3748980"); 

Judging by the name of your variable - the account - I assume that you are dealing with money. You should not use floating point types to represent money. Use BigDecimal or possibly int

+11
source

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

+3
source

You are using Integer.parseInt for a decimal number - this is not a valid integer - visible in your stack trace

+2
source

All Articles