Android NumberFormatException: Invalid Double - ex

2019-02-18 14:17发布

问题:

So the other day, the following error popped up in the Crashes section of the Google Play Developer Console:

java.lang.NumberFormatException: Invalid double: "−0.05"

Now correct me if I'm wrong, but that is in fact a valid double - and it is recognised as a valid double on my computer, on the emulator and on my own Android device (Nexus 5)

The device that it crashed on was a Galaxy Note II running Android 4.3 - any ideas as to why it might be crashing please?

回答1:

It is or isn't a valid double depending on your Locale. With a US/ENGLISH locale, -0.05 is a valid double but with a FRENCH locale for example, it is not (it should be -0,05 with a comma).

You can see it in action with:

NumberFormat fmt = NumberFormat.getNumberInstance(Locale.US);
double d = fmt.parse("-0.05").doubleValue(); //-0.05

fmt = NumberFormat.getNumberInstance(Locale.FRENCH);
d = fmt.parse("-0.05").doubleValue(); //-0.0
d = fmt.parse("-0,05").doubleValue(); //-0.05

EDIT

However your issue is maybe not that. The minus sign is not valid. You are using instead of - (they look the same but are not the same character). Demo:

Double.parseDouble("-0.05"); //ok
Double.parseDouble("−0.05"); //exception


回答2:

For double constants, the language asks you to use the form -0.05d (with the "d" suffix). See this for reference

Also make sure that the symbol intended to be a minus sign is a "hyphen" and not a "long em dash".