我正在尝试像这样打印 INR 格式的货币:
NumberFormat fmt = NumberFormat.getCurrencyInstance();
fmt.setCurrency(Currency.getInstance("INR"));
fmt.format(30382.50);
显示Rs30,382.50
,但在印度它写成Rs. 30,382.50
(见http://www.flipkart.com/)如何在不硬编码 INR 的情况下解决?
我正在尝试像这样打印 INR 格式的货币:
NumberFormat fmt = NumberFormat.getCurrencyInstance();
fmt.setCurrency(Currency.getInstance("INR"));
fmt.format(30382.50);
显示Rs30,382.50
,但在印度它写成Rs. 30,382.50
(见http://www.flipkart.com/)如何在不硬编码 INR 的情况下解决?
这有点骇人听闻,但在非常相似的情况下,我使用了类似这样的东西
NumberFormat format = NumberFormat.getCurrencyInstance(new Locale("en", "in"));
String currencySymbol = format.format(0.00).replace("0.00", "");
System.out.println(format.format(30382.50).replace(currencySymbol, currencySymbol + " "));
我必须处理的所有货币都涉及到小数点后两位,所以我可以"0.00"
为所有这些货币做,但如果你打算使用像日元这样的货币,这必须进行调整。有一个NumberFormat.getCurrency().getSymbol()
;但它会返回INR
for ,Rs.
因此不能用于获取货币符号。
看看这是否有效:
DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance();
fmt.setGroupingUsed(true);
fmt.setPositivePrefix("Rs. ");
fmt.setNegativePrefix("Rs. -");
fmt.setMinimumFractionDigits(2);
fmt.setMaximumFractionDigits(2);
fmt.format(30382.50);
编辑:修复了第一行。
一种更简单的方法,一种解决方法。对于我的语言环境,货币符号是“R$”
public static String moneyFormatter(double d){
DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance();
Locale locale = Locale.getDefault();
String symbol = Currency.getInstance(locale).getSymbol(locale);
fmt.setGroupingUsed(true);
fmt.setPositivePrefix(symbol + " ");
fmt.setNegativePrefix("-" + symbol + " ");
fmt.setMinimumFractionDigits(2);
fmt.setMaximumFractionDigits(2);
return fmt.format(d);
}
输入:
moneyFormatter(225.0);
输出:
"R$ 225,00"
我没有看到任何简单的方法来做到这一点。这就是我想出的...
获取实际货币符号的关键似乎是将目标语言环境传递给 Currency.getSymbol:
currencyFormat.getCurrency().getSymbol(locale)
下面是一些看起来最有效的代码:
public static String formatPrice(String price, Locale locale, String currencyCode) {
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(locale);
Currency currency = Currency.getInstance(currencyCode);
currencyFormat.setCurrency(currency);
try {
String formatted = currencyFormat.format(NumberFormat.getNumberInstance().parse(price));
String symbol = currencyFormat.getCurrency().getSymbol(locale);
// Different locales put the symbol on opposite sides of the amount
// http://en.wikipedia.org/wiki/Currency_sign
// If there is already a space (like the fr_FR locale formats things),
// then return this as is, otherwise insert a space on either side
// and trim the result
if (StringUtils.contains(formatted, " " + symbol) || StringUtils.contains(formatted, symbol + " ")) {
return formatted;
} else {
return StringUtils.replaceOnce(formatted, symbol, " " + symbol + " ").trim();
}
} catch (ParseException e) {
// ignore
}
return null;
}