Java BigDecimal:四舍五入到最接近的整数值
我需要以下结果
100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00
.round()
或 .setScale()
?我该怎么办?
I need the following results
100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00
.round()
or .setScale()
? How do I go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用
setScale()
将小数位数减少到零。假设value
保存要舍入的值:使用
round()
有点复杂,因为它要求您指定要保留的位数。在您的示例中,该值为 3,但这并非对所有值都有效:(请注意,
BigDecimal
对象是不可变的;setScale
和round
将返回一个新对象。)You can use
setScale()
to reduce the number of fractional digits to zero. Assumingvalue
holds the value to be rounded:Using
round()
is a bit more involved as it requires you to specify the number of digits to be retained. In your examples this would be 3, but this is not valid for all values:(Note that
BigDecimal
objects are immutable; bothsetScale
andround
will return a new object.)如果我按照 Grodriguez 的回答,
这就是输出
,这并不完全是我想要的,所以我最终这样做了..
这就是我得到的,
这暂时解决了我的问题..:)
谢谢大家。
If i go by Grodriguez's answer
This is the output
Which isn't quite what i want, so i ended up doing this..
This is what i get
This solves my problem for now .. : )
Thank you all.
这是一个非常复杂的解决方案,但它有效:
测试代码:
输出:
Here's an awfully complicated solution, but it works:
Test Code:
Output:
只需查看:
http://download.oracle .com/javase/6/docs/api/java/math/BigDecimal.html#ROUND_HALF_UP
并且:
或者如果使用 Java 6,则
http://download.oracle.com/javase/6/docs/api/java/math/RoundingMode.html#HALF_UP< /a>
http://download.oracle.com/ javase/6/docs/api/java/math/MathContext.html
以及:
Simply look at:
http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#ROUND_HALF_UP
and:
Or if using Java 6, then
http://download.oracle.com/javase/6/docs/api/java/math/RoundingMode.html#HALF_UP
http://download.oracle.com/javase/6/docs/api/java/math/MathContext.html
and either:
我不认为你可以用一个命令来像这样舍入它。尝试
我测试了你的其余示例,它返回了想要的值,但我不保证它的正确性。
I don't think you can round it like that in a single command. Try
I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.
如果
.round()
和.setScale()
对您来说都不直观,您可以使用此代码舍入到任何整数步精度(例如,以 10 秒、25 秒舍入) 、50 秒、100 秒……)。用法:
声明:
可以根据需要将尾随
.00
附加到结果中。If neither
.round()
nor.setScale()
seem intuitive to you, you can use this code to round to any integer steps of precision (e.g. round in 10s, 25s, 50s, 100s, ...).Usage:
Declaration:
Trailing
.00
can be appended to the result on demand.你想要
You want