Encountering NumberFormatException

2019-08-17 13:19发布

问题:

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.