1

I would like to know if it's possible for us to add commas on BigDecimal while retaining number of decimals and trailing zeros?

1111.90 --> 1,111.90
1234.010 --> 1,234.010
938938.1223 --> 938,938.1223

I tried using DecimalFormat and it seems to be removing trailing zeros.

DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();

symbols.setGroupingSeparator(',');
formatter.setDecimalFormatSymbols(symbols);
System.out.println(formatter.format(bd));
stackyyflow
  • 767
  • 3
  • 11
  • 30
  • 1
    Does this answer your question? [How to set thousands separator in Java?](https://stackoverflow.com/questions/5323502/how-to-set-thousands-separator-in-java) – rajah9 Jan 25 '22 at 14:13
  • 3
    You could try setting `formatter.setMinimumFractionDigits(bd.scale());` and see if that gives you the result you want. (Should work for most values, but I haven't tested it and make no guarantees) – OH GOD SPIDERS Jan 25 '22 at 14:17

1 Answers1

0

Try this(java):

String.format("%,." + bigDecimal.scale() + "f", bigDecimal);

Try this(kotlin):

String.format("%,.${bigDecimal.scale()}f", bigDecimal)

Also you can remove trailing zeros by this:

bigDecimal = bigDecimal.stripTrailingZeros()

and then use above codes.

Alger
  • 33
  • 7