How to fix java.lang.NumberFormatException: For input string: ".52"

Viewed 35

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

1 Answers

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);

shorter version due to comments :)

etString = "0" + etLength.getText().toString();
if (etString.contains(".")) etString +=0;

assuming your EditText have proper filter (android:inputType)and won't allow multiple decimal separators . and ,

note that in some languages it's a dot, in other is a coma, you may check what is set on running OS with

char separator = DecimalFormatSymbols.getInstance().getDecimalSeparator();

but still you can't be shure that used keyboard respects that (oftnly keyboards always enter .), so check for both characters

Related