I'm working on an international project and have observed that, in Java, the choice of the decimal separator is based on the Locale's language, not its country. For example:
DecimalFormat currencyFormatter = (DecimalFormat) NumberFormat.getInstance(new Locale("it","IT"));
System.out.println(currencyFormatter.format(-123456.78));
currencyFormatter = (DecimalFormat) NumberFormat.getInstance(new Locale("en","IT"));
System.out.println(currencyFormatter.format(-123456.78));
produces the following output:
-123.456,78
-123,456.78
I would have expected it to follow the country, since if I'm in the country, whether I speak English or Italian the numbers in that country are written with the decimal separator as comma.
My question is two-fold:
- Does anyone know why this behaviour follows the language?
- More importantly, can anyone offer details as to how to modify the default behaviour in Java to follow the language instead?
Thanks.
But if you are an Englishman living in Italy, chances are you still write your numbers the English way and count your money in pounds inside your head - and vice versa ;-)
So to me this behaviour looks perfectly logical. And I am afraid there may not be a way to get what you want :-(
Update based on the comment of Oscar Reyes: In Java 6, NumberFormatProvider enables you to achieve your goal.
Your assumption "I would have expected it to follow the country, since if I'm in the country, whether I speak English or Italian the numbers in that country are written with the decimal separator as comma." is wrong. Several bilingual countries have language specific formatting rules for numbers. Among the countries with formatting rules in Sun's JDK, this applies to Canada, India and Luxembourg.
As people have noted, the problem is most likely that java can't find your exact local, so it went to what it thought was closest. If you do have a DecimalFormat object, you can manually change the separators if you'd like.
Modifying all of Java is a big order; as far as I know, there's no way to do this at the JVM level. However, you can manually set the number format for your particular classes/projects to pretty much any locale (or even imaginary system) with the DecimalFormatSymbols class. See "Altering the Formatting Symbols" at the Java Tutorials page on format customization for examples and more information.
Granted, this is not an optimal approach if your program might be used in more than three or four different locations, but it could work if you're only supporting a few.
No. Some countries with many official languages such as Canada (two official languages) have different formatting convention based on the language:
I think you might be able to override the NumberFormat behavior per Locale using LocaleServiceProvider. This would require Java 6 though ...