How to print formatted BigDecimal values?

2019-01-04 09:51发布

I have a BigDecimal field amount which represents money, and I need to print its value in the browser in a format like $123.00, $15.50, $0.33.

How can I do that?

(The only simple solution which I see myself is getting floatValue from BigDecimal and then using NumberFormat to make two-digit precision for the fraction part).

5条回答
太酷不给撩
2楼-- · 2019-01-04 10:22

Another way which could make sense for the given situation is

BigDecimal newBD = oldBD.setScale(2);

I just say this because in some cases when it comes to money going beyond 2 decimal places does not make sense. Taking this a step further, this could lead to

String displayString = oldBD.setScale(2).toPlainString();

but I merely wanted to highlight the setScale method (which can also take a second rounding mode argument to control how that last decimal place is handled. In some situations, Java forces you to specify this rounding method).

查看更多
家丑人穷心不美
3楼-- · 2019-01-04 10:35

To set thousand separator, say 123,456.78 you have to use DecimalFormat:

     DecimalFormat df = new DecimalFormat("#,###.00");
     System.out.println(df.format(new BigDecimal(123456.75)));
     System.out.println(df.format(new BigDecimal(123456.00)));
     System.out.println(df.format(new BigDecimal(123456123456.78)));

Here is the result:

123,456.75
123,456.00
123,456,123,456.78

Although I set #,###.00 mask, it successfully formats the longer values too. Note that the comma(,) separator in result depends on your locale. It may be just space( ) for Russian locale.

查看更多
爷的心禁止访问
4楼-- · 2019-01-04 10:37
 BigDecimal pi = new BigDecimal(3.14);
 BigDecimal pi4 = new BigDecimal(12.56);

 System.out.printf("%.2f",pi);

// prints 3.14

System.out.printf("%.0f",pi4);

// prints 13

查看更多
时光不老,我们不散
5楼-- · 2019-01-04 10:40
BigDecimal(19.0001).setScale(2, BigDecimal.RoundingMode.DOWN)
查看更多
时光不老,我们不散
6楼-- · 2019-01-04 10:49
public static String currencyFormat(BigDecimal n) {
    return NumberFormat.getCurrencyInstance().format(n);
}

It will use your locale to choose your currency symbol. NumberFormat's javadoc

查看更多
登录 后发表回答