如何将数字的小数组成部分,因此它不影响整个数字的一部分?
我有这个bigdecimal数字 - 68.65121847597993
,我想像这样将其舍入 - 68.7
,因此只有小数点的小数零件才能全面舍入,但不是整数。
我尝试使用coundingmode.half_up,但它也将整个数字填写。 有没有办法仅使用Java组合数字的小数部分?
I have this BigDecimal number - 68.65121847597993
and I want to round it like this - 68.7
, so only decimical part of number would be rounded up, but not the whole number.
I tried to use RoundingMode.HALF_UP but it rounds up the whole number as well.
Is there a way to round up only decimical part of number using java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
为了表示有很多小数点的数字,我认为您正在使用
bigdecimal
而不是double
,它只能准确地表示大约从 bigdecimal 用字符串,双重或其他任何东西初始化,您可以调用 bigdecimal :: setScale 获得所需的值。
例如:
In order to represent a number with that many decimal points, I presume you are using
BigDecimal
rather thandouble
, which can only accurately represent approximately 15 significant digits.Starting from a BigDecimal, which you can initialize with a string, a double, or anything else you have, you can call BigDecimal::setScale to get the value you want.
For example:
我几乎在其他所有语言中都这样做:
使用
bigdecimal
,您有更多选项,例如圆形模式和setScale
,如果需要的话。还有第三方库,例如 decimal4j 或 apache commons数学 - 尽管我没有测试它们。
I would do it as in nearly every other language:
With a
BigDecimal
you have more options like a rounding mode andsetScale
if you need that.And there are third party libraries like decimal4j or Apache Commons Math - though I didn't test them.
您应该尝试
以下是一篇关于它的贝尔登文章:
https://wwwww.baeldung.com/java-round-decimal-decimal-number
希望它有帮助!
You should try this
Here's a Baeldung article about it:
https://www.baeldung.com/java-round-decimal-number
Hope it helps!
您不能真正这样做,因为浮动和双打无法正常工作。
但是,这可以解决您的问题:
另请参阅: Java Float 123.129456到123.12,没有四舍五入
You cannot really do that because floats and doubles do not work like that.
However, this could solve your problem:
also see: Java float 123.129456 to 123.12 without rounding
如果您的价值是双重的,则此方法在编译时需要最低的时间:
0 =小数的数量
If your value is a double, this method takes the lowest time on compiling:
Number of 0's = number of decimals
尝试一下
Try this
与其更改数字(因此仍可以在后续计算中使用其当前精度),您可以按照以下方式控制显示。
印刷
Rather than change the number (so its current precision can be still used in subsequent calculations), you can control the display as follows.
prints