How to print formatted BigDecimal values?
public static String currencyFormat(BigDecimal n) {
return NumberFormat.getCurrencyInstance().format(n);
}
It will use your JVM’s current default Locale
to choose your currency symbol. Or you can specify a Locale
.
NumberFormat.getInstance(Locale.US)
For more info, see NumberFormat
class.
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.
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).