我尝试了很多。但是无法找到解决方案。 我有一个格式化货币的代码。我使用以下代码:
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);
我在这里遇到了一个问题。 考虑一个法国语言环境的案例。在我的例子中,语言环境可以是en_FR和fr_FR。
DecimalFormatSymbols decimalFormats = new DecimalFormatSymbols();
decimalFormats.setCurrencySymbol(currencySymbol);
((DecimalFormat) numberFormat).setDecimalFormatSymbols(decimalFormats);
formattedCurrency = numberFormat.format(Double.valueOf(number));
因此,如果语言环境是en_FR,则formattedCurrency值将为€10.00,如果语言环境为fr_FR,则值为10.00€。
所以我想知道语言代码在这个计算方法中的作用。因为en_FR有en,我猜它默认采用en_US。因此价格左边的货币符号。
如果国家是法国,无论语言代码如何,我都需要获得10.00欧元。是否有其他方法可以根据国家而不是区域设置来获取货币格式?
答案 0 :(得分:1)
只需指定国家/地区代码,而不是语言和国家/地区
尝试为您修改如下:
String countryCode="FR"; // or use "String countryCode=Locale.getDefault().getCountry();" for system default locale
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(new Locale(countryCode));
注意:强>
区域设置指向语言而不是特定于国家/地区,上述代码将在ISO国家/地区代码和语言代码相同的大多数情况下按预期工作。
答案 1 :(得分:0)
您只需将FRANCE
指定为Locale
,它就会始终在右侧打印出来。
String formattedCurrency = DecimalFormat.getCurrencyInstance(Locale.FRANCE).format(10.00);
输出:
10,00€
修改强>
您可以获取用户的Locale
:
Locale currentLocale = Locale.getDefault();
并将其作为参数传递:
String formattedCurrency = DecimalFormat.getCurrencyInstance(currentLocale).format(10.00);
我不在法国,但对我来说它会打印出来:
€10.00
这对爱尔兰来说是正确的。
第二次编辑:
您可以通过获取显示国家/地区,从上面的currentLocale
获取国家/地区名称 - 但这会存储为String
String country = currentLocale.getDisplayCountry();
然后将其转换为Locale
以用作参数
public static Locale getLocaleFromString(String localeString) {
return new Locale(localeString, "");
}
注意:此方法是来自here
的已修改代码段然后在格式化程序中使用它
Locale l = getLocaleFromString(country);
String number = DecimalFormat.getCurrencyInstance(l).format(10.00);