Search code examples
androiddoublenumber-formattingseparator

Invalid double in converting String to Double


i get a NumberFormatException : invalid double "111,000,000" in this line of code :

double SalePotential = Double.valueOf(EtPotential.getText().toString());

in the beginning i've used Numberformat , to format my double value for separating number and inserted it to an EditText but when i try to retrieve the value of EditText it throws me the exception :

NumberFormat f = NumberFormat.getInstance();
EtPotential.setText(String.valueOf(f.format(PTData.SalePotential)));

i've also tried DecimalFormat or Double.parseDouble with no Success. any help would be Appreciated! :

DecimalFormat f = new DecimalFormat("###.###", DecimalFormatSymbols.getInstance());
double SalePotential = Double.parseDouble(EtPotential.getText().toString());

Solution

  • Remove "," before parsing

    double SalePotential = Double.parseDouble(EtPotential.getText().toString().replace(",", ""));
    

    Update : With proper implementation

    double salePotential = 0; // Variable name should start with small letter 
    try {
        salePotential = Double.parseDouble(EtPotential.getText().toString().replace(",", ""));
    } catch (NumberFormatException e) {
        // EditText EtPotential does not contain a valid double
    }
    

    Happy coding :)