Monday, November 4, 2013

Parsing a String representation of Double with comma decimal separator in Android cause NumberFormatException

I've used the same code parsing a String representation of Double with comma decimal separator (e.g. "0,3") on different versions of Android (2.3 and 4.*). It is strange, but in Android 2.3 the code was executed without any Exception, but in Android 4.* I've got NumberFormatException with the message: Invalid Double: 0,3

I've fixed it by replacement of comma for a dot separator in String object of my Double:

DecimalFormat newFormat = new DecimalFormat("#.#");

double result = 0;
   try {
       String doubleString = newFormat.format(constancyPercentage);
        result = Double.parseDouble(doubleString.replace(",", "."));//0,3 -> 0.3
} catch (NumberFormatException e) {
//TODO show nothing
}