2

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)

5
  • 4
    hint: 5,828 could be a float depending on your LOCALE Commented May 15, 2017 at 7:37
  • What is your LOCALE? Commented May 15, 2017 at 7:40
  • change your input string from 5,828 to 5.828 Commented May 15, 2017 at 7:40
  • it the same problem if i let dot and what is a LOCALE ? Commented May 15, 2017 at 7:42
  • See docs.oracle.com/javase/7/docs/api/java/text/… the Locale defines officially used format of numbers, dates, time, etc. I'd use the DataFormat class and with the correct Local it could infer that "," is as well a decimal separator Commented May 15, 2017 at 7:44

4 Answers 4

4

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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 ,.

Comments

0

Try this

NumberFormat.getNumberInstance(Locale.FRANCE).parse("5,828");

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.