How to print formatted BigDecimal values?

I have a BigDecimal amount field, which is money, and I need to print its value in the browser in the format $123.00 , $15.50 , $0.33 .

How can i do this?

(The only simple solution I can see for myself is to get a floatValue from BigDecimal , and then use NumberFormat to make double-digit precision for part of the fraction).

+90
java formatting number-formatting bigdecimal
Aug 03 '10 at 10:57
source share
6 answers
 public static String currencyFormat(BigDecimal n) { return NumberFormat.getCurrencyInstance().format(n); } 

It will use the current default values ​​for your JVM Locale to select a currency symbol. Or you can specify Locale .

 NumberFormat.getInstance(Locale.US) 

For more information, see the NumberFormat class.

+116
Aug 03 '10 at 11:01
source share

To set the thousands separator, say 123,456.78 you must 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 the mask to #,###.00 , it successfully formats longer values ​​as well. Note that the comma separator (,) as a result depends on your locale. It may just be a space () for the Russian locale.

+57
Jul 21 '15 at 5:45
source share

Another way that might make sense for a given situation is to

 BigDecimal newBD = oldBD.setScale(2); 

I just say this, because in some cases, when it comes to money that goes beyond 2 decimal places, it makes no sense. Taking this even further can lead to

 String displayString = oldBD.setScale(2).toPlainString(); 

but I just wanted to highlight the setScale method (which can also take the second argument of the rounding mode to control the processing of the last decimal place. In some situations, Java forces you to specify this rounding method).

+33
Dec 20 2018-11-21T00:
source share
  BigDecimal pi = new BigDecimal(3.14); BigDecimal pi4 = new BigDecimal(12.56); System.out.printf("%.2f",pi); 

// print 3.14

 System.out.printf("%.0f",pi4); 

// prints 13

+10
Sep 20 '17 at 3:46 on
source share

Similar to @Jeff_Alieffson's answer, but does not rely on Locale by default:

Use DecimalFormatSymbols for the explicit language:

 DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance(new Locale("ru", "RU")); 

Or explicit delimiter characters:

 DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(); decimalFormatSymbols.setDecimalSeparator('.'); decimalFormatSymbols.setGroupingSeparator(' '); 

Then:

 new DecimalFormat("#,##0.00", decimalFormatSymbols).format(new BigDecimal("12345")); 

Result:

 12 345.00 
+2
May 6 '19 at 11:54
source share
 BigDecimal(19.0001).setScale(2, BigDecimal.RoundingMode.DOWN) 
+1
Jun 26 '16 at 6:51
source share



All Articles