将BigDecimal格式化为带有三个小数位的货币字符串

时间:2016-10-11 10:01:50

标签: java

我需要将数字格式化为货币。问题是我需要三位小数。

此刻我有两个。我的代码是:

private static Locale getLocaleFromCurrency(String strCode) {

    for (final Locale locale : NumberFormat.getAvailableLocales()) {
        final String code = NumberFormat.getCurrencyInstance(locale).getCurrency().getCurrencyCode();
        if (strCode.equals(code)) {
            return locale;
        }
    }  
    return null;
}

private String toCurrency(BigDecimal value, String currency) {
    if (value == null) {
        value = new BigDecimal(0);
    }
    return NumberFormat.getCurrencyInstance(getLocaleFromCurrency(currency)).format(value);
}

目前,我得到了:

$1.24
$10.20

但我想收到:

$1.242
$10.195

2 个答案:

答案 0 :(得分:3)

使用NumberFormat方法setMaximumFractionDigitssetMinimumFractionDigits

NumberFormat numberFormat = NumberFormat.getCurrencyInstance(getLocaleFromCurrency(currency));
numberFormat.setMaximumFractionDigits(3);
numberFormat.setMinimumFractionDigits(3);
return numberFormat.format(value);

答案 1 :(得分:1)

您可以使用setMinimumFractionDigits(3)类的format.setMaximumFractionDigits(3)NumberFormat

相关问题