使用语言环境(languageCode,countryCode)格式化BigDecimal为特定于语言环境的货币字符串

5
我正在使用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;
}

根据Oracle文档,运行环境没有要求每个区域设置敏感类都必须支持所有语言环境。每个区域设置敏感类实现自己对一组语言环境的支持,而这个集合可以因类而异。例如,数字格式类可以支持不同于日期格式类的语言环境集。
由于用户输入了languageCode和countryCode,如果用户输入错误,例如,languageCode=de,countryCode=US,那么该怎么处理(或者说NumberFormat.getCurrencyInstance方法如何处理)?
它是否默认为某个语言环境?应该如何处理这种情况?
谢谢。

1
这个答案这样的东西对你有用吗? - artie
是的,看起来可以使用LocaleUtils.isAvailableLocale。 - HopeKing
1个回答

6

根据 @artie 的建议,我正在使用 LocaleUtil.isAvailableLocale 来检查区域设置是否存在。如果它是无效的区域设置,我将其默认为 en_US。这在一定程度上解决了问题。

然而,这仍然不能解决检查 NumberFormat 是否支持该区域设置的问题。如果有任何其他解决此问题的答案,我将接受。

   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;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接