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).
Another way which could make sense for the given situation is
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
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).
To set thousand separator, say
123,456.78
you have to use DecimalFormat:Here is the result:
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.// prints 3.14
// prints 13
It will use your locale to choose your currency symbol. NumberFormat's javadoc