NumberFormatException for String while parsing float

This error is probably caused due to my different system locale. I use DOT as decimal separator.

I tried to set a default locale when my application starts but I'm getting the same exception.

Locale.setDefault(Locale.US);

Stacktrace:

 Caused by: java.lang.NumberFormatException: For input string: "6,2" at
 sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043) at
 sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)  at
 java.lang.Float.parseFloat(Float.java:451)
Jon Skeet
people
quotationmark

It looks like your code is using Float.parseFloat. That doesn't use any locale settings. From the docs:

Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.

And valueOf has a detailed grammar, and includes this:

To interpret localized string representations of a floating-point value, use subclasses of NumberFormat.

So basically, your default locale is irrelevant here. If you want to parse "6,2" you should be using a NumberFormat with a locale using comma as a decimal separator.

people

See more on this question at Stackoverflow