0

I have to set up my BigDecimal values at 2 places with different format.

1st One : If there are trailing zeroes then just have 1 digit after decimal and if not then just do mode as floor

eg.
1250.348 -> 1250.34
1250.0000 -> 1250.0
1250.50 -> 1250.5

So, I am trying something like this

BigDecimal value = new BigDecimal("1250.348");
value = value.setScale(2, RoundingMode.FLOOR); //I get 1250.34 which is proper

But it doesnt work for 1250.50 or 1250.000

2nd One : I just want to remove all zeroes decimal

1250.000->1250
1250.50->1250.5

Can someone tell me how can I do this ?

s shah
  • 1
  • Does this answer your question? [How to print formatted BigDecimal values?](https://stackoverflow.com/questions/3395825/how-to-print-formatted-bigdecimal-values) – JGFMK Mar 27 '20 at 21:08
  • Do you want to actually change the scale of the numbers, or is this used for formatting for display only? – Joni Mar 27 '20 at 21:08
  • @Joni For display only – s shah Mar 27 '20 at 21:10
  • @JGFMK No, one solution is same as mine, but it doesnt work for all – s shah Mar 27 '20 at 21:17

1 Answers1

1

Use DecimalFormat. In your first case you want the format pattern 0.0#.

import java.text.DecimalFormat;

DecimalFormat formatter = new DecimalFormat("0.0#");
formatter.setRoundingMode(RoundingMode.FLOOR);

formatter.format(new BigDecimal("1250.348"));

In the second case, you'll want to use format pattern 0.##.

Joni
  • 108,737
  • 14
  • 143
  • 193