Format a BigDecimal as String with max 2 decimal d

2019-01-08 13:10发布

I have a BigDecimal number and i consider only 2 decimal places of it so i truncate it using:

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

Now I want to print it as String but removing the decimal part if it is 0, for example:

1.00 -> 1

1.50 -> 1.5

1.99 -> 1.99

I tried using a Formatter, formatter.format but i always get the 2 decimal digits.

How can I do this? Maybe working on the string from bd.toPlainString()?

5条回答
时光不老,我们不散
2楼-- · 2019-01-08 13:41
new DecimalFormat("#0.##").format(bd)
查看更多
等我变得足够好
3楼-- · 2019-01-08 13:42

If its money use:

NumberFormat.getNumberInstance(java.util.Locale.US).format(bd)
查看更多
ら.Afraid
4楼-- · 2019-01-08 13:50

Use stripTrailingZeros().

This article should help you.

查看更多
Viruses.
5楼-- · 2019-01-08 13:57

I used DecimalFormat for formatting the BigDecimal instead of formatting the String, seems no problems with it.

The code is something like this:

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);
查看更多
仙女界的扛把子
6楼-- · 2019-01-08 14:00

The below code may help you.

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);
}
查看更多
登录 后发表回答