Rob Rob - 7 months ago 48
Java Question

Java override locale setting for specific locale

I'm using

to format currency from a BigDecimal to a string. This works as expected the problem is that our main target is the dutch market and the default dutch formatting is strange.

Let me explain, when formatting -125 I get "€ 125-" for dutch (expected was "-€125"). Uk works as expected giving "-£125.50".

I could check if the locale is Dutch and then supply a pattern each time I want to format decimals. But I would prefer a solution that overrides the dutch formatting settings. I was thinking about something like the following:

Locale nlLocale = new Locale("nl", "NL");
NumberFormat.getCurrencyInstance(new Locale("nl", "NL")).setFormatPattern("€ #");

So that each time I use the dutch locale when formatting I get my custom format. Does a similar solution exists?


Leaving aside the question of whether that particular format is "correct" or not, the way to change the currency instance for the "nl" locale is to implement and configure a custom LocaleServiceProvider for the number format service. (The provider class needs to subclass NumberFormatProvider, but the superclass javadoc explains how to configure the provider.)

The provider needs to return a non-standard NumberFormat instance for the particular case you are concerned about, but (presumably) delegate to the default provider in other cases.