How to print formatted BigDecimal values?
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).
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).