Java – NumberFormatException on the European version of Android?

NumberFormatException on the European version of Android?… here is a solution to the problem.

NumberFormatException on the European version of Android?

I have an application that runs the following two lines of code at startup:

DecimalFormat decim = new DecimalFormat("#.00");
return Double.parseDouble(decim.format(totalNumberOfCredits));

When I launch the app on my US phone, decim.format(totalNumberOfCredits) has a value of .00.

However, in my Google Play Developer Console, I encountered more than a dozen crashes, all of which looked like this:

Caused by: java.lang.NumberFormatException: Invalid double: ",00"
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:269)
at java.lang.Double.parseDouble(Double.java:295)

Is it really possible for DecimalFormat to generate comma versions of decimals on European phones?

Solution

Is it really possible that DecimalFormat is producing a comma version of the decimal on European phones?

Yes, absolutely. That’s it< a href="http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html#DecimalFormat%28java.lang.String%29" rel="noreferrer noopener nofollow">meant to do , after all:

Creates a DecimalFormat using the given pattern and the symbols for the default locale. This is a convenient way to obtain a DecimalFormat when internationalization is not the main concern.

To obtain standard formats for a given locale, use the factory methods on NumberFormat such as getNumberInstance. These factories will return the most appropriate sub-class of NumberFormat for a given locale.

Note that this is not an issue with “Android in Europe” – it is just an issue of using Android in the context of the default locale using as a decimal separator.

If you want to use locale-specific symbols, but use specific patterns, you can use:

DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.US);
DecimalFormat format = new DecimalFormat("#.00", symbols);

That being said, it’s not clear to you what you’re going to do at first – why format and then parse the numbers? You should almost always avoid string conversions when you really don’t need them. Why not convert it directly? (We don’t know what totalNumberOfCredits is, and that doesn’t help.) )

Related Problems and Solutions