Java decimal format parsing issue

public class NumFormatTest { public static void main(String[] args) throws ParseException { String num = "1 201"; DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRANCE); System.out.println("Number Before parse: "+num); double dm = df.parse(num).doubleValue(); System.out.println("Number After parse: "+dm); } } 

Output:

  Number Before parse: 1 201 Number After parse: 1.0 

Expected Result:

  Number Before parse: 1 201 Number After parse: **1201** 

Can someone help me understand why the parser cannot convert a formatted string in FRENCH format (1 201) to a normal double value (1201.0)?

+6
source share
4 answers

There are two types of spaces. โ€œNormalโ€ space (No. 32 - HEX 0x20) and non-breaking space (NBSP) (No. 160 - HEX 0xA0).

For some reason (I donโ€™t know why), the French locale expects the space character between numbers to be non-expanding space! You can help yourself with this line of code:

 String num = "1 201"; num = num.replaceAll(" ", "\u00A0"); // '\u00A0' is the non breaking whitespace character! 

This way your code will work as expected. Please note: if you format double in String with French, the resulting space character will be NBSP too !!!

 DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRENCH); System.out.println(df.format(1201.1)); // This will print "1 202,1" But the space character will be '\u00A0'! 
+5
source

In fact, Java uses an unbreakable character space ( \u00a0 ) to parse French numbers.

Thus, the following code actually works:

 String num = "1\u00a0201"; double dm = df.parse(num).doubleValue(); System.out.println("Number After parse: " + dm); 

See @ParkerHalo answer for more details.

+3
source

you can use

  String num = "1 201"; DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRANCE); System.out.println("Number Before parse: "+num); DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); symbols.setGroupingSeparator(' '); df.setDecimalFormatSymbols(symbols); double dm = df.parse(num).doubleValue(); System.out.println("Number After parse: "+dm); 

Expected Result:

 Number Before parse: 1 201 Number After parse: 1201.0 
+2
source

This seems to work.

 public double parse(String decimalAsText) { NumberFormat decimalFormat = NumberFormat.getNumberInstance(Locale.FRANCE); decimalAsText = decimalAsText.replace(' ', '\u00a0'); ParsePosition pp = new ParsePosition(0); Number n = decimalFormat.parse(decimalAsText, pp); return n.doubleValue(); } 
+1
source

All Articles