gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:51:29 25 4
gpt4 key购买 nike

我正在使用 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 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.

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

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

谢谢。

最佳答案

根据@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;
}

关于java - 使用 Locale(languageCode, countryCode) 将 BigDecimal 格式化为 Locale 特定的货币字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46997969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com