5

I am converting a BigDecimal currency value to a locale specific Currency Format using the Locale(languageCode, countryCode) constructor as shown in the code below

public static String formatCurrency(BigDecimal amount, String languageCode, String countryCode) {

    Format format = NumberFormat.getCurrencyInstance(new Locale(languageCode, countryCode));
    String formattedAmount = format.format(amount);
    logger.debug("Orginal Amount {} and Formatted Amount {}", amount, formattedAmount);
    return formattedAmount;
}

Now as per the excellent resource at Oracle Docs

The runtime environment has no requirement that all locales be supported equally by every locale-sensitive class. Every locale-sensitive class implements its own support for a set of locales, and that set can be different from class to class. For example, a number-format class can support a different set of locales than can a date-format class.

Since my languageCode and countryCode are entered by User, how do I handle the situation (or rather how does the NumberFormat.getCurrencyInstance method handle it) when a user enters wrong input like say, languageCode = de and countryCode = US.

Does it default to some Locale ? How does one handle this situation.

Thanks.

HopeKing
  • 3,317
  • 7
  • 39
  • 62
  • 1
    Will something like [this answer](https://stackoverflow.com/questions/3684747/how-to-validate-a-locale-in-java) work for you? – artie Oct 29 '17 at 09:03
  • Yes, looks like LocaleUtils.isAvailableLocale could be used. – HopeKing Oct 29 '17 at 17:12

1 Answers1

6

Based on suggestion from @artie, I am using LocaleUtil.isAvailableLocale to check if the locale exists. If it is an invalid Locale I dafult it to en_US. That solves the problem to some extent.

However, it still doesn't solve the problem of checking if the NumberFormat supports that Locale. Will accept any other answer that solves this issue.

   public static String formatCurrency(BigDecimal amount, String languageCode, String countryCode) {

        Locale locale = new Locale(languageCode, countryCode);
        if (!LocaleUtils.isAvailableLocale(locale)) {
            locale = new Locale("en", "US");
        }
        Format format = NumberFormat.getCurrencyInstance(locale);
        String formattedAmount = format.format(amount);
        logger.debug("Orginal Amount {} and Formatted Amount {}", amount, formattedAmount);
        return formattedAmount;
    }
HopeKing
  • 3,317
  • 7
  • 39
  • 62