Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 784
Roman Avatar asked Aug 03 '10 10:08

Roman


People also ask

Can BigDecimal have commas?

BigDecimal doesn't have a dot or a comma.

How do I round off BigDecimal?

BigDecimal. round(MathContext mc) returns a BigDecimal rounded according to the MathContext settings. If the precision setting is 0 then no rounding takes place.

How do I remove trailing zeros from BigDecimal?

stripTrailingZeros() is an inbuilt method in Java that returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. So basically the function trims off the trailing zero from the BigDecimal value.


1 Answers

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.

like image 112
Luca Molteni Avatar answered Sep 17 '22 13:09

Luca Molteni