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: http://blog.ej-technologies.com/2011/12/default-locale-changes-in-java-7.html 

 

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;
df.applyPattern(“#.##”); 
 
//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 - http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7073906 


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:

Popular micro services patterns

Here are some popular Microservice design patterns that a programmer should know: Service Registry  pattern provides a  central location  fo...