Why does a German localised DecimalFormat successfully parse "3.2" as a decimal in Java?

Viewed 93

I would expect that

var decimal = DecimalFormat.getInstance(locale).parse(number);

yields a ParseException when the locale is de_DE and the number is "3.2" as "." is not a valid separater for this Locale. Why is this? Wasn't the idea of a Locale that all these formatting questions are handled in a standardised way?

2 Answers

FULL STOP effectively has no meaning in German numeric parsing

As commented, the FULL STOP (.) character in German is a thousands grouping mark (not a decimal separator). Its use is not semantic, it has no meaning. DecimalFormat does not enforce any rules about grouping a certain number of digits.

So in your code the dot is effectively ignored. The 3 and the 2 are considered as if they are 32, and therefore parsed as thirty-two.

Example code.

//Locale locale = Locale.US ;      // Parses FULL STOP as a decimal separator, with 3.2 as result. 
Locale locale = Locale.GERMANY ;   // Parses FULL STOP as a digit grouping, with 32 as result.
String input = "3.2" ;
var decimal = DecimalFormat.getInstance( locale ).parse( input );
System.out.println( decimal ) ;

See this code run live at IdeOne.com.

32

It will successfully parse it even with a different character instead of .. See the JavaDoc of NumberFormat.parse:

Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.

As long as the input starts with 3 the parse method will always succeed for your locale. (Are there locales that don't understand Arabic digits even?)

Related