Java – Android NumberFormatException : Invalid Double – except the value is a valid Double

Android NumberFormatException : Invalid Double – except the value is a valid Double… here is a solution to the problem.

Android NumberFormatException : Invalid Double – except the value is a valid Double

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

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

Correct me if I’m wrong, but this is actually a valid stand-in – it is recognized as a valid stand-in on my computer, emulator, and my own Android device (Nexus 5).

The device it crashed

on was a Galaxy Note II running Android 4.3 – please know why it crashed?

Solution

It is or is not a valid double depending on your locale. For the US/ENGLISH locale, -0.05 is a valid double value, but for the FRENCH locale, it is not (it should be -0,05 with a comma).

You can see it in action in the following ways:

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

But your problem may not be like that. The minus sign is invalid. You are using – instead of - (they look the same but the characters are different). Demo:

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

Related Problems and Solutions