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?