Home > Software design >  How to fix java.lang.NumberFormatException: For input string: ".52"
How to fix java.lang.NumberFormatException: For input string: ".52"

Time:09-16

Hi, I am getting userInput from three editTexts and setting it to a TextView after multiplying.

This is the code :

  float l = Float.parseFloat(etLength.getText().toString());
  float b = Float.parseFloat(etBreadth.getText().toString());
  float d = Float.parseFloat(etDepth.getText().toString());
  pitSize.setText(String.valueOf(l * b * d));

If I type 0.52, then the code works, but if I type .52 the App crashes with this exception :

 java.lang.NumberFormatException: For input string: ".52"

Please let me know how to fix this Issue. Thanks

CodePudding user response:

well, just don't allow such string, this is not a number in fact... for human it is readable and "understandable", for electronic device floating point is BETWEEN numbers, not at the beginning or end

just detect if first/last character is a dot . and add then 0 before/after

String etString = etLength.getText().toString();
if (etString.startsWith(".")) {
    etString = "0"   etString
}
if (etString.endsWith(".")) {
    etString = etString   "0";
}
float l = Float.parseFloat(etString);
  • Related