Invalid Double. Number format exception in android

2019-09-21 11:45发布

问题:

I have this in xml.

<EditText
                android:id="@+id/creditlimitfield2"
                android:hint="0"
                android:inputType="numberDecimal" />

So, the default value for edittext is 0.

in code, I have this

creditlimit = (EditText) findViewById(R.id.creditlimitfield2);
double credit_limit = Double.valueOf(creditlimit.getText().toString());

Alternately, I have tried:

double credit_limit = Double.parseDouble(creditlimit.getText().toString());

And

double credit_limit = new Double(creditlimit.getText().toString());

When I run the program, It gives the error of

Numberformatexception. Invalid double "".

Please be reminded that the field is not empty. Any suggestions would be helpful.


I have seen many questions,almost similar to it, with very less answers and none of them help solving my condition. So, Please do not tag it as "Similar Question" without checking other questions too.

回答1:

getText() does not return the value inside android:hint. So you are trying to convert an empty string as double. use android:text property instead.

<EditText
    android:id="@+id/creditlimitfield2"
    android:text="0"
    android:inputType="numberDecimal" />


回答2:

Looks like creditlimit.getText().toString() does not a return a valid double value. Make sure you enter a valid double in the EditText.

Numberformatexception. Invalid double ""

Empty string is not a valid double.

Also i guess you have this just after initialization make sure you get the text from edittext on button click or in onResume

double credit_limit = Double.valueOf(creditlimit.getText().toString())

If you want the default value follow blackbelt's post.



回答3:

try this
Sting limit=creditlimit.getText().toString(); double credit_limit =0; if(limit!=null && !limit.isEmpty()){ credit_limit = Double.parseDouble(limit); }