1

End-users are provided with a list of currencies. One of which of their interest may be selected by them at any time. As such, a locale used in java.text.NumberFormat needs to be changed based on the currency selected. This does not appear to be trivial.

Locale locale = new Locale("en", "US");
NumberFormat decimalFormat = NumberFormat.getCurrencyInstance(locale);
decimalFormat.setGroupingUsed(true);
decimalFormat.setCurrency(Currency.getInstance("USD"));

System.out.println(decimalFormat.format(BigDecimal.valueOf(1.12)));

The piece of code above will display the correct currency value $1.12. Since currency (and locale) is determined dynamically at run-time based on the user's preference, if USD is changed to something different like GBP, then the associated locale also needs to be changed from en_US to en_GB. Otherwise, it will display GBP1.12 where £1.12 is expected (the currency rate is excluded for brevity).

Is there a way to determine the locale based on the currency code which is supplied dynamically at run-time?

Tiny
  • 27,221
  • 105
  • 339
  • 599

1 Answers1

1

If you only support a limited number of currencies then you are probably better off creating the mapping manually. Otherwise it's going to be difficult because there is more than one valid locale per currency. For example USD can be en_US or es_US or es_PR or es_EC...

You can look at Currency.getInstance(locale) for all Locale.availableLocales() to get an idea:

for (Locale locale : Locale.getAvailableLocales()) {
  try {
    Currency c = Currency.getInstance(locale);
    System.out.println(c + "\t" + locale);
  } catch (IllegalArgumentException ignore) { }
}
assylias
  • 321,522
  • 82
  • 660
  • 783