NumberFormatException on European Versions of Andr

2019-05-13 18:05发布

问题:

I have an app which runs the following two lines of code upon starting:

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

When I start the app on my American phone, the value of decim.format(totalNumberOfCredits) is .00.

However, in my Google Play Developer Console, I have a dozen crashes, all of which look 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 that DecimalFormat is producing a comma version of the decimal on European phones?

回答1:

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

Yes, absolutely. That's what it's 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 isn't a matter of a "European version of Android" - it's just a matter of using Android in a context where the default locale uses , as the decimal separator.

If you want to use the symbols for a particular locale, but using a specific pattern, you could use:

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

Having said that, it's not at all clear what you're trying to do in the first place - why would you format and then parse a number? You should almost always avoid string conversions when you don't really need them. Why not just convert it directly? (We don't know what totalNumberOfCredits is, which doesn't help.)



回答2:

    public double getTwoPointDecimal(double value) {        
           DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);      
           return Double.parseDouble(new DecimalFormat("##.##", symbols).format(value));
    }

try it, its help me in my project



回答3:

double unit = Float.parseFloat(String); DecimalFormat decimal = new DecimalFormat("##.###").format(unit);

try this it help me in my project