SilverShotBee SilverShotBee - 1 month ago 11
Android Question

Android Float.parseFloat results in a fatal error due to decimal point

I'm using the following code to parse a float from a string:

EditText CurrPLC = (EditText) findViewById(R.id.CurrPLC);
String s5 = CurrPLC.getText().toString();
float F5 = Float.parseFloat(s5);


This works great until I try to write a negative value into the
EditText
. Because the "negative" symbol is on the same button as the decimal point, I write a decimal first and then the app crashes because a string of "." cannot be parsed into a float value. The code is executed on any text change in the
EditText


Here's the
EditText
code from the layout file:

<EditText
android:id="@+id/CurrPLC"
android:layout_width="100dp"
android:layout_height="30dp"
android:padding="2dp"
android:hint="eg. 3277"
android:gravity="center_horizontal"
android:layout_gravity="right"
android:textSize="13sp"
android:digits="-0123456789."
android:inputType="numberSigned|numberDecimal"
android:maxLength="10"
android:background="@drawable/plc_edit_text_holo_light"
android:layout_marginRight="19dp"
android:layout_marginEnd="19dp"
android:layout_alignBaseline="@+id/CurrPLCLabel"
android:layout_alignBottom="@+id/CurrPLCLabel"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
/>


Is there something I've done wrong, or is this simply down to handling this before the error occurs?

Thanks

Answer

Based on your comment of using a TextWatcher which would attempt to parse the float on each key press, the problem is not with negative numbers.

parseFloat() will work fine with negative numbers. The problem is with an empty string or -, -., or . most likely.

So you should not parse on each key press and instead only do it wherever you need it (I'm not sure of your full use case so I can't comment on the appropriate time and place to parse the float). Otherwise you need to add a try/catch for java.lang.NumberFormatException wherever you are currently parsing the float.