Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top