Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java override locale setting for specific locale

Tags:

java

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?

like image 652
Rob Avatar asked Nov 04 '22 13:11

Rob


1 Answers

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.

like image 88
Stephen C Avatar answered Nov 12 '22 16:11

Stephen C