使用 Locale(languageCode, countryCode) 将 BigDecimal 格式化为 Locale 特定的货币字符串

Hop*_*ing 4 java formatting locale currency internationalization

我正在使用 Locale(languageCode, countryCode) 构造函数将 BigDecimal 货币值转换为特定于语言环境的货币格式,如下面的代码所示

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;
}
Run Code Online (Sandbox Code Playgroud)

现在根据Oracle Docs 上的优秀资源

运行时环境不要求每个区域设置敏感类都平等地支持所有区域设置。每个对语言环境敏感的类都实现自己对一组语言环境的支持,并且该集合可以因类而异。例如,数字格式类可以支持与日期格式类不同的一组语言环境。

由于我的 languageCode 和 countryCode 是由用户输入的,当用户输入错误的输入时,我如何处理这种情况(或者说 NumberFormat.getCurrencyInstance 方法如何处理它),比如 languageCode = de 和 countryCode = US。

它是否默认为某些 Locale ?这种情况如何处理。

谢谢。

Hop*_*ing 5

根据@artie 的建议,我正在使用 LocaleUtil.isAvailableLocale 来检查语言环境是否存在。如果它是一个无效的语言环境,我将它改为 en_US。这在一定程度上解决了问题。

但是,它仍然没有解决检查 NumberFormat 是否支持该 Locale 的问题。将接受解决此问题的任何其他答案。

   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;
    }
Run Code Online (Sandbox Code Playgroud)