Thursday, March 07, 2013

Java 7 Locale Changes impacting Double.parseDouble() for some European Locales

Details on the Java 7 Locale related changes and its impact is captured succinctly at: 


A fix for the old code using Double.parseDouble() method which used to work fine with European locales like French (fr) and German (de) are broken since the parseDouble() method considers the value being passed to it to be in English format whereas a decimal value in French/German is represented with a comma and not a dot thus leading to a NumberFormatException. Prior to Java 7, the behavior for parseDouble() method was to expect the value to be in the current locale and not en_US.

A fix to the above issue is:

Locale loc = Locale.getDefault(Locale.Category.FORMAT); // get current locale
NumberFormat nf = NumberFormat.getNumberInstance(loc); // get number format for current locale
DecimalFormat df = (DecimalFormat)nf;
//Then replace occurrence of Double.parseDouble(df.format(c)) with the following:
Number number = nf.parse(df.format(c)); // parse the decimal string for current locale
System.out.println("Formt using NumberFormat "+ number.doubleValue());

According to Oracle, this is not a bug but a feature enhancement - 

The enhancement was done to have the flexibility to write multi-lingual applications (applications showing data in more than one locale). Earlier entire application would default to just one selected locale.

No comments:

15 sorting algorithms visualized in 5 minutes, with awesome arcade sounds

15 sorting algorithms visualized in 5 minutes, with awesome arcade sounds from r/programming