Java BigDecimal Rounding while having pointless 0's in the number

Viewed 128

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?

2 Answers

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.

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

Related