8

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

Arif YILMAZ
  • 5,496
  • 25
  • 95
  • 184

8 Answers8

14

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

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

That should work.

JREN
  • 3,512
  • 3
  • 25
  • 44
5

You have added comma instead of '.'

Do like this.

float f1 = Float.parseFloat("1.9698");
Avadhani Y
  • 7,476
  • 18
  • 59
  • 90
Rachita Nanda
  • 4,389
  • 9
  • 40
  • 64
4
Hope this will help you..

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

Or In one line-

    float float_no = Float.parseFloat("3.1427");
Vaishali Sharma
  • 670
  • 3
  • 6
  • 24
1

This is Type Conversion: type conversion required when we use different type of data in any variables.

    String str = "123.22";

    int i = Integer.parseInt(str);
    float f = Float.parseFloat(str);
    long l = Long.parseLong(str);
    double d= Double.parseDouble(str);

    str = String.valueOf(d);
    str = String.valueOf(i);
    str = String.valueOf(f);
    str = String.valueOf(l);

Also some times we need Type Casting: type casting required when we use same data but in different type. only you cast Big to Small Datatype.

    i = (int)f;
    i = (int)d;
    i = (int)l;

    f = (float)d;
    f = (float)l;

    l = (long)d;
Mr.Sandy
  • 4,169
  • 3
  • 28
  • 53
1

used this float f1 = Float.parseFloat("1.9698"); or replace ,(comma) with .(dot) that is invalid form of flot number

1
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();
}
HebeleHododo
  • 3,609
  • 1
  • 28
  • 38
Makvin
  • 3,083
  • 24
  • 26
1

In kotlin:

stringValue.toFloatOrNull() ?: 0F

Which will give NumberFormatException free conversion.

More precise:

private fun getFloat(stringValue: String) = stringValue.toFloatOrNull() ?: 0F
vishnu benny
  • 774
  • 7
  • 14
1

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());
    }
}
bko
  • 36
  • 3