BigDecimal四舍五入问题
我希望能够将任何数字四舍五入到整数的四分之一。
例如:
100.33 -> 100.50 100.12 -> 100.25 100.66 -> 100.75 100.99 -> 101.00 100.70 -> 100.75 100.00 -> 100.00 100.25 -> 100.25
等等...
谢谢大家...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这会满足您的需要:乘以 4,向上舍入,然后除以 4。
This does what you need: it multiplies by 4, rounds up, then divides back by 4.
我认为如果没有一些手动干预这是不可能的。您可以通过传入 MathContext 到 BigDecimal 构造函数;但是,该类的对象中使用的舍入模式必须是 RoundingMode 枚举常量(并且这些都没有实现您想要的舍入类型)。如果这是一个您可以编写自己的定义的接口,那就太好了,但您已经有了它。
根据代码所需的性能,您当然可以将数字乘以 4,四舍五入到最接近的整数,然后再次除以 4。这可能是最少的实际编程工作,并且相对容易理解,因此如果您的代码不在性能关键部分,这就是我的建议。
I don't believe this is possible without some manual intervention. You get to specify the rounding settings by passing in a MathContext to the BigDecimal constructor; however, the rounding mode used in an object of that class has to be a RoundingMode enum constant (and none of those implement the kind of rounding you want). It would be nice if this was instead an interface that you could write your own definition of, but there you have it.
Depending on how performant your code needs to be, you could of course multiply the number by 4, round up to the nearest whole number, and divide by 4 again. This is probably the least actual programming effort and is relatively easily understandable, so if your code isn't in a performance-critical section it's what I'd suggest.
Math.round(x.doubleValue() * 4) / 4
或
Math.ceil
或Math.floor
取决于你想要的Math.round(x.doubleValue() * 4) / 4
or
Math.ceil
orMath.floor
depending on what you want