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).
BigDecimal doesn't have a dot or a comma.
BigDecimal. round(MathContext mc) returns a BigDecimal rounded according to the MathContext settings. If the precision setting is 0 then no rounding takes place.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With