Java 货币符号和金额之间需要空格
我正在尝试打印INR格式的货币,如下所示:Java 货币符号和金额之间需要空格,java,currency-formatting,Java,Currency Formatting,我正在尝试打印INR格式的货币,如下所示: NumberFormat fmt = NumberFormat.getCurrencyInstance(); fmt.setCurrency(Currency.getInstance("INR")); fmt.format(30382.50); 显示的是rs30382.50,但在印度,其书写形式为Rs.30382.50(参见) 如何在不使用INR硬编码的情况下解决此问题?查看此方法是否有效: DecimalFormat fmt = (DecimalF
NumberFormat fmt = NumberFormat.getCurrencyInstance();
fmt.setCurrency(Currency.getInstance("INR"));
fmt.format(30382.50);
显示的是rs30382.50
,但在印度,其书写形式为Rs.30382.50
(参见)
如何在不使用INR硬编码的情况下解决此问题?查看此方法是否有效:
DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance();
fmt.setGroupingUsed(true);
fmt.setPositivePrefix("Rs. ");
fmt.setNegativePrefix("Rs. -");
fmt.setMinimumFractionDigits(2);
fmt.setMaximumFractionDigits(2);
fmt.format(30382.50);
编辑:修复了第一行。这有点像黑客,但在非常类似的情况下,我使用了类似的方法
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
而不是Rs.
,因此不能用于获取货币符号。我认为您不能
你应该看看
icu4j可能会提供更好的特定于语言环境的货币格式。我看不到任何简单的方法可以做到这一点。这是我想到的 获取实际货币符号的关键似乎是将目标区域设置传递到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;
}
一种更简单的方法,一种变通方法。 对于我的语言环境,货币符号是“R$” 输入:
moneyFormatter(225.0);
输出:
"R$ 225,00"
这看起来像是硬编码。不适用于负数-符号和负号之间添加了一个空格。因为我找不到一个在数字和后面有货币的符号之间没有空格的区域设置(例如,
123.45$
),所以我只在符号后面添加一个空格,而不是在前面。(StringUtils.replaceOnce(格式化、符号、符号+).trim();
)
"R$ 225,00"