问题描述
我想将Java BigDecimal
舍入到一定数量的有效数字(不保留小数位),例如到4位数字:
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
等基本问题是如何找到BigDecimal
的数量级,因此我可以决定在小数点后使用多少个位置.
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.
我能想到的就是一个可怕的循环,除以10,直到结果为< 1,我希望有更好的方法.
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.
推荐答案
最简单的解决方案是:
int newScale = 4-bd.precision()+bd.scale();
BigDecimal bd2 = bd1.setScale(newScale, RoundingMode.HALF_UP);
不需要字符串转换,它完全基于BigDecimal
算术,因此,可以选择RoundingMode
,它尽可能地高效,它很小.如果输出应为String
,只需附加.toPlainString()
.
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()
.
这篇关于使用BigDecimal限制有效数字的任何巧妙方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!