java decimal限制,使用BigDecimal限制有效数字的任何巧妙方法

I want to round a Java BigDecimal to a certain number of significant digits (NOT decimal places), e.g. to 4 digits:

12.3456 => 12.35

123.456 => 123.5

123456 => 123500

etc. The basic problem is how to find the order of magnitude of the BigDecimal, so I can then decide how many place to use after the decimal point.

All I can think of is some horrible loop, dividing by 10 until the result is <1, I am hoping there is a better way.

BTW, the number might be very big (or very small) so I can't convert it to double to use Log on it.

解决方案

The easierst solution is:

int newScale = 4-bd.precision()+bd.scale();

BigDecimal bd2 = bd1.setScale(newScale, RoundingMode.HALF_UP);

No String conversion is necessary, it is based purely on BigDecimal arithmetic and therefore as efficient as possible, you can choose the RoundingMode and it is small. If the output should be a String, simply append .toPlainString().

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值