Why Integer.parseInt of a String representing a number throws java.lang.NumberFormatException in J2ME?

我是研究僧i 提交于 2019-12-02 14:08:23

问题


I want to sum the values of four columns of a recordstore. The values in these four columns are numbers with the decimal point , for example 30.00; the recordstore row is a csv-like data with which I use a userdefined function to get the value of a particular column: so I get a String for the four columns , for example "30.00". Now I want to sum these four values ; so I must convert them into int ! But when I attempt to use Integer.parseInt then the java.lang.NumberFormatException is raised ! So how to make the sum in this situation ?


回答1:


Even though 30.00 seems like an integer to you, Java thinks it looks like a floating point value (due to the decimal point).

You therefore need to parse it as a double, and then get the integer part.

int i = Double.parseDouble("30.00").intValue();

(Not J2ME specific by the way.)




回答2:


If your numbers contain decimal points, you need to parse as a double.

Double.parseDouble("30.00");

From there you can use Math methods or just truncate to get your Integer.




回答3:


Just as another alternative, you could also use Integer.parseInt("30.00".split("\\.")[0])
This would remove dependency on decimal separator (if you always have a dot in string, but you have no control on locale it will be parsed on.



来源:https://stackoverflow.com/questions/9214004/why-integer-parseint-of-a-string-representing-a-number-throws-java-lang-numberfo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!