将BigDecimal格式化为字符串,最多2位小数,小数部分删除0

时间:2012-04-22 15:04:16

标签: java formatting bigdecimal

我有一个BigDecimal数字,我只考虑它的2位小数,所以我用以下方法截断它:

bd = bd.setScale(2, BigDecimal.ROUND_DOWN)

现在我想将其打印为String,但如果为0则删除小数部分,例如:

1.00 - > 1

1.50 - > 1.5

1.99 - > 1.99

我尝试使用Formatter,formatter.format,但我总是得到2位小数。

我该怎么做?也许正在处理来自bd.toPlainString()的字符串?

5 个答案:

答案 0 :(得分:88)

我使用DecimalFormat格式化BigDecimal而不是格式化String,似乎没有问题。

代码是这样的:

bd = bd.setScale(2, BigDecimal.ROUND_DOWN);

DecimalFormat df = new DecimalFormat();

df.setMaximumFractionDigits(2);

df.setMinimumFractionDigits(0);

df.setGroupingUsed(false);

String result = df.format(bd);

答案 1 :(得分:57)

new DecimalFormat("#0.##").format(bd)

答案 2 :(得分:9)

使用stripTrailingZeros()

This文章可以帮助您。

答案 3 :(得分:9)

以下代码可能会对您有所帮助。

protected String getLocalizedBigDecimalValue(BigDecimal input, Locale locale) {
    final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
    numberFormat.setGroupingUsed(true);
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setMinimumFractionDigits(2);
    return numberFormat.format(input);
}

答案 4 :(得分:3)

如果用钱:

NumberFormat.getNumberInstance(java.util.Locale.US).format(bd)