I am trying to convert string to float but I couldnt succeed.
here is my code
float f1 = Float.parseFloat("1,9698");
the error it gives is
Invalid float "1,9698";
why is it doing this? it is a valid float
We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.
Convert String to Float in Kotlin/AndroidThe toFloat() method converts the string to a Float, It throws the NumberFormatException exception when the string is not a legitimate representation of a Float.
We can convert String to float in java using Float. parseFloat() method.
Integer floatValue() Method in Java Return Type: A numeric value represented by this object after converting it to type float.
You are using a comma when you should be using a period
float f1 = Float.parseFloat("1.9698");
That should work.
You have added comma instead of '.'
Do like this.
float f1 = Float.parseFloat("1.9698");
Float number;
String str=e1.getText().toString();
number = Float.parseFloat(str);
Or In one line
float float_no = Float.parseFloat("3.1427");
Float total = Float.valueOf(0);
try
{
total = Float.valueOf(str);
}
catch(NumberFormatException ex)
{
DecimalFormat df = new DecimalFormat();
Number n = null;
try
{
n = df.parse(str);
}
catch(ParseException ex2){ }
if(n != null)
total = n.floatValue();
}
I suggest you use something like this:
String text = ...;
text = text.replace(",", ".");
if(text.length() > 0) {
try {
float f = Float.parseFloat(text);
Log.i(TAG, "Found float " + String.format(Locale.getDefault(), "%f", f));
} catch (Exception e) {
Log.i(TAG, "Exception " + e.toString());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With