Reputation: 5866
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
Upvotes: 8
Views: 39608
Reputation: 602
Float number;
String str=e1.getText().toString();
number = Float.parseFloat(str);
Or In one line
float float_no = Float.parseFloat("3.1427");
Upvotes: 3
Reputation: 106
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());
}
}
Upvotes: 3
Reputation: 1058
In kotlin:
stringValue.toFloatOrNull() ?: 0F
Which will give NumberFormatException free conversion.
More precise:
private fun getFloat(stringValue: String) = stringValue.toFloatOrNull() ?: 0F
Upvotes: 1
Reputation: 3629
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();
}
Upvotes: 2
Reputation:
used this float f1 = Float.parseFloat("1.9698"); or replace ,(comma) with .(dot) that is invalid form of flot number
Upvotes: 1
Reputation: 4349
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;
Upvotes: 1
Reputation: 4659
You have added comma instead of '.'
Do like this.
float f1 = Float.parseFloat("1.9698");
Upvotes: 5
Reputation: 3630
You are using a comma when you should be using a period
float f1 = Float.parseFloat("1.9698");
That should work.
Upvotes: 15