Reputation: 43
I'm trying to parse a String to a float with the float.parsefloat()
method but it gives me an error concerning the format.
int v_CurrentPosX = Math.round(Float.parseFloat(v_posString)); //where v_posString is the float that I want to convert in this case 5,828
And the error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "5,828" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043) at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
Upvotes: 2
Views: 7738
Reputation: 48287
Your problem is that colon (,) is not a default locale in the JVM...
you can use a NumberFormat for that, with the right locale
String x = "5,828";
NumberFormat myNumForm = NumberFormat.getInstance(Locale.FRENCH);
double myParsedFrenchNumber = (double) myNumForm.parse(x);
System.out.println("D: " + myParsedFrenchNumber);
Upvotes: 4
Reputation: 1305
Float.parseFloat() doesn't consider locale and always expects '.' to be your decimal point separator. You can use DecimalFormat instead.
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
String str = "5,200";
DecimalFormat format = new DecimalFormat("0.#");
format.setDecimalFormatSymbols(symbols);
float f = format.parse(str).floatValue();
Upvotes: 0
Reputation: 12572
Try this
NumberFormat.getNumberInstance(Locale.FRANCE).parse("5,828");
Upvotes: 0
Reputation: 1220
Try replacing the comma with a dot before parsing like so:
v_posString = v_posString.replace(",",".");
int v_CurrentPosX = Math.round(Float.parseFloat(v_posString));
The problem is that your locale is set to use .
for floats and not ,
.
Upvotes: 0