3

Problem

I used BigDecimal.setScale(7, RoundingMode.HALF_UP) to round the number to 7 decimal places, however now if I get a number without any decimal places or with them being fewer then 7 I get useless 0's in the number, for example after rounding 40 that way I'll get 40.0000000.

Question

Is it possible to round numbers a certain number of decimal places using SetScale and get rid of pointless 0's at the same time?

blackbrandt
  • 2,010
  • 1
  • 15
  • 32
  • Does this answer your question? [How to round a number to n decimal places in Java](https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – blackbrandt Aug 02 '21 at 13:06

2 Answers2

5

Providing you have already performed your rounding, you can simply use DecimalFormat("0.#").

final double value = 5.1000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(value));

The result here will be 5.1 without the trailing zeroes.

blackbrandt
  • 2,010
  • 1
  • 15
  • 32
Daniel Scarfe
  • 256
  • 1
  • 7
  • this solution atually worked, but I found another one and I wonder is DecimalFormat any better then using `.stripTrailingZeros().toPlainString()` ? – agingcabbage32 Aug 02 '21 at 13:16
  • 2
    @mmmetafool In this circumstance, their results are identical and it comes down to coding preference. `DecimalFormat` is more powerful if you later decide you want to change your level of precision / formatting style. Your solution uses fewer lines. – Daniel Scarfe Aug 02 '21 at 13:19
  • 1
    @mmmetafool I suggest you post that other solution as another Answer to your Question. – Basil Bourque Aug 02 '21 at 16:17
1

So the other way to work this problem out is using BigDecimals methods such as .stripTrailingZeros().toPlainString() It is quite lesser code to write, than the other solution, but as said iт the solution could be less comfortable to change level of precision in the future, if you'll need to