使用 BigDecimal 限制有效数字的任何巧妙方法
我想将 Java BigDecimal
舍入到一定数量的有效数字(不是小数位),例如 4 位数字:
12.3456 => 12.35 123.456 => 123.5 123456 => 123500
等等。基本问题是如何找到 的数量级BigDecimal
,这样我就可以决定小数点后使用多少位。
我能想到的只是一些可怕的循环,除以 10 直到结果 <1,我希望有更好的方法。
顺便说一句,这个数字可能非常大(或非常小),所以我无法将其转换为双精度以使用 Log 。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
为什么不直接使用round(MathContext)呢?
Why not just use
round(MathContext)
?最简单的解决方案是:
不需要字符串转换,它纯粹基于 BigDecimal 算术,因此为了尽可能高效,您可以选择 RoundingMode 并且它很小。如果输出应该是
String
,只需附加.toPlainString()
。The easierst solution is:
No String conversion is necessary, it is based purely on
BigDecimal
arithmetic and therefore as efficient as possible, you can choose theRoundingMode
and it is small. If the output should be aString
, simply append.toPlainString()
.您可以使用以下行:
注意:此解决方案始终向下舍入到最后一位数字。
You can use the following lines:
Note: this solution always rounds down to the last digit.
有人可能会想出更好的解决方案,但首先想到的是将其放入 StringBuilder 中,检查它是否包含“.”。并返回适当长度的子字符串。例如:
Someone will probably come up with a better solution, but the first thing that comes to mind is chuck it in to a StringBuilder, check whether it contains a '.' and return an appropriate length substring. E.g.:
对我来说,这似乎很简单:
给定 N = 5,D = 123.456789
阶数可以使用 Math.floor(Math.log(D)) 计算。
希望这有帮助。
To me this seems as simple as:
Given N = 5, D = 123.456789
Order can be calculated using Math.floor(Math.log(D)).
hope this helps.
由于 BigDecimal 基本上是一个字符串,也许是这样:
产生这样的结果:
Since BigDecimal is basically a string, perhaps this:
Which produces this:
AH的答案在技术上是正确的,但这里有一个更通用(也更容易理解)的解决方案:
A.H.'s answer is technically correct, but here is a more general (and easier to understand) solution: