Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 747
agingcabbage32 Avatar asked Mar 10 '26 12:03

agingcabbage32


1 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.

like image 160
Daniel Scarfe Avatar answered Mar 12 '26 01:03

Daniel Scarfe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!