需要货币符号和金额之间的空间
我正在尝试打印INR格式的货币,如下所示:
NumberFormat fmt = NumberFormat.getCurrencyInstance(); fmt.setCurrency(Currency.getInstance("INR")); fmt.format(30382.50);
显示Rs30,382.50
,但在印度它写为Rs. 30,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
而不是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);
编辑:修复了第一行。
我没有看到任何简单的方法来做到这一点。 这就是我想出来的……
获取实际货币符号的关键似乎是将目标语言环境传递给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; }
我不认为你可以。
你应该看看http://site.icu-project.org/
icu4j可能提供更好的特定于语言环境的货币格式。
一种更简单的方法,一种变通方法。 对于我的区域设置,货币符号为“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"