Rob
Rob

Reputation: 2666

Java override locale setting for specific locale

I'm using NumberFormat.getCurrencyInstance().format(amount) 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?

Upvotes: 5

Views: 2951

Answers (2)

ballzak
ballzak

Reputation: 708

Use the applyPattern method:

final DecimalFormat df = (DecimalFormat)NumberFormat.getCurrencyInstance(locale);
df.applyPattern("¤#,##0.##");

Upvotes: 0

Stephen C
Stephen C

Reputation: 718708

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.

Upvotes: 2

Related Questions