Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to float in android

Tags:

java

android

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

like image 472
Arif YILMAZ Avatar asked Jun 25 '13 07:06

Arif YILMAZ


People also ask

How do you convert a string to a 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.

How do I change a string to a float in Kotlin?

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.

Can I convert string to float in Java?

We can convert String to float in java using Float. parseFloat() method.

Which method is used to convert value to float?

Integer floatValue() Method in Java Return Type: A numeric value represented by this object after converting it to type float.


5 Answers

You are using a comma when you should be using a period

float f1 = Float.parseFloat("1.9698");

That should work.

like image 104
JREN Avatar answered Oct 18 '22 00:10

JREN


You have added comma instead of '.'

Do like this.

float f1 = Float.parseFloat("1.9698");
like image 5
Rachita Nanda Avatar answered Oct 18 '22 00:10

Rachita Nanda


Float number;
String str=e1.getText().toString();
number = Float.parseFloat(str);

Or In one line

float float_no = Float.parseFloat("3.1427");
like image 3
Vaishali Sharma Avatar answered Oct 18 '22 00:10

Vaishali Sharma


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();
}
like image 2
Makvin Avatar answered Oct 18 '22 00:10

Makvin


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());
    }
}
like image 1
bko Avatar answered Oct 17 '22 22:10

bko