NumberFormatException Error

前端 未结 5 1509
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 08:48

the code is:

editText2=(EditText) findViewById(R.id.editText2);
editText3=(EditText) findViewById(R.id.editText3);
float from_value= Float.parseFloat(editTe         


        
相关标签:
5条回答
  • 2020-12-11 08:59

    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 !

    0 讨论(0)
  • 2020-12-11 09:01

    IMHO you are entering some non float value which is causing this error.

    0 讨论(0)
  • 2020-12-11 09:03

    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 ??
    }
    
    0 讨论(0)
  • 2020-12-11 09:05

    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.

    0 讨论(0)
  • 2020-12-11 09:14

    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.

    0 讨论(0)
提交回复
热议问题