简体   繁体   中英

NumberFormatException Error

the code is:

editText2=(EditText) findViewById(R.id.editText2);
editText3=(EditText) findViewById(R.id.editText3);
float from_value= Float.parseFloat(editText2.getText().toString());
editText3.setText(" "+(from_value * 100.0));

And the logcat error is:

03-18 03:19:07.847: E/AndroidRuntime(875): Caused by: java.lang.NumberFormatException: Invalid float: ""

Seems like the String in editText2 is empty, so it fails to parse it as float.

A possible solution is to check if the String is empty first, and then decide about default value, another is to catch the exception:

float from_value;
try {
    from_value = Float.parseFloat(editText2.getText().toString());
}
catch(NumberFormatException ex) {
    from_value = 0.0; // default ??
}

You should try to avoid using try/catch if at all possible because it is not the preferred method.

The correct way to avoid this error is to stop it before it happens.

if (mEditText.getText().toString().equals("")) {
    value = 0f;
} else {
    value = Float.parseFloat(mEditText.getText().toString()); 
}

Update: Since you are using EditText , the simplest way to avoid the NumberFormatException is to specify the inputType attribute so that it will only accept numbers. XML example: android:inputType="number" . Though, you may still get a value larger (or smaller) that the data type can't hold.

Then, depending on your use case, you could even step up a level by using a custom "IntEditText" or custom InputFilter so that you can specify a min and max, and re-use the code across apps.

to me the best way is to do it like this:

editText2=(EditText) findViewById(R.id.editText2);
editText3=(EditText) findViewById(R.id.editText3);

if(!editText2.getText().toString().matches("")){
float from_value= Float.parseFloat(editText2.getText().toString());
editText3.setText(" "+(from_value * 100.0));
}

And also add this line to your xml for editText2

android:inputType="numberDecimal"

Hope it helps !

Probably a good idea to validate the value you are reading from editText2 before parsing it to float. Make sure it is a valid number first.

恕我直言,你输入一些非浮动值导致此错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM