Search code examples
javaandroidparsingdoublenumberformatexception

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


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?


Solution

  • 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