Convert string to float in android

I am trying to convert a string to float, but I could not succeed.

here is my code

float f1 = Float.parseFloat("1,9698"); 

the mistake she gives is

 Invalid float "1,9698"; 

why is he doing this? this is a valid float

+6
source share
6 answers

You use a comma when you should use a period

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

That should work.

+10
source

You have added a comma instead of "."

Do so.

 float f1 = Float.parseFloat("1.9698"); 
+5
source
 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"); 
+4
source

This is Type Conversion : type when we use different data types 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); 

We also need Type Casting : type, when we use the same data, but in different types. only you impose the type "large" on the "small".

  i = (int)f; i = (int)d; i = (int)l; f = (float)d; f = (float)l; l = (long)d; 
+1
source

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

+1
source
 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(); } 
+1
source

Source: https://habr.com/ru/post/948038/


All Articles