Anurag Kamble Anurag Kamble - 6 months ago 16
Android Question

Remove extra dots in float value before a separater " , " occurs using java

I am generating a statistical calculator application.

So I want to format input from edittext like this
i/p = 3.5.6, 6.5 to 3.5 , 6.5

Using " , " (comma) as separator so splitting the input string to float array when a " , " occurs.

I want to ignore 3.5[.6] and generate array like this
s[1] = 3.5 , s[2] = 6.5

While calculating mean application crashes due to extra " . " dots.

s = it.getText().toString(); //"it" is edittext
s=s.replaceAll( ",+" , "," );
String[] strarray =s.split(",");

float[] farray = new float[strarray.length];
for(int i = 0; i < strarray.length; i++)
{
farray[i] = Float.parseFloat(strarray[i]);
}


--DEBUG LOGCAT--

W/dalvikvm(3051): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid float: "6.7."
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseFloat(StringToReal.java:310)
at java.lang.Float.parseFloat(Float.java:300)
at com.cal.mc2.Mean$1.onClick(Mean.java:67)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)`
`at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Force finishing activity com.cal.mc2/.Mean

Answer

How about this simple function (IdeOne link here: https://ideone.com/utKPjP):

public static float myParseFloat(String str) {
    int firstDot = str.indexOf('.');
    if (firstDot != -1) {
        int secondDot = str.indexOf('.', firstDot+1);
        return Float.parseFloat(secondDot == -1 ? str : str.substring(0,secondDot));
    }
    return Float.parseFloat(str);
}

Then you just replace this statement in your code:

farray[i] = Float.parseFloat(strarray[i]);

with:

farray[i] = myParseFloat(strarray[i]);