Encountering NumberFormatException

本小妞迷上赌 提交于 2019-12-12 04:59:35

问题


I am trying to convert a string to a double but get a NumberFormatException.

Here is my code:

String x = "";
// String ary[]=new String[10];
while (finalstr.charAt(stpr) != ' ') {
    // System.out.print(finalstr.charAt(stpr));
    Character c = new Character(finalstr.charAt(stpr));

    String s = c.toString(c);
    ary[i] = s;
    x = x + ary[i];
    i++;

    stpr++;
    // first++;
}
// System.out.print(x);
String yo = x;
// System.out.print(yo); //it prints well
// double d = Double.valueOf(yo.trim()).doubleValue();
double doubleprim = Double.parseDouble(yo);
System.out.print(doubleprim);

All help appreciated.


回答1:


try Double.valueOf(yo.trim()).doubleValue();




回答2:


Oh crap such an ugly code! However, if I get it correctly you are trying to construct string of all characters in finalstr until an interval is encountered.

Use this code:

String [] splits = finalstr.split(" ");
double doubleprim = Double.parseDouble(splits[0]);

From then on if you get th eNumberFormat exception, it is due to wrong string value, not anything else.




回答3:


You can try this . It Worked for me :

               CharSequence cs = amount.getText();
                if(cs!=null && cs.length()>0)
                {
                double pro = Double.parseDouble(cs.toString());
                }

here as you can see amount is an edittext which i am using in android.



来源:https://stackoverflow.com/questions/9443882/encountering-numberformatexception

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