How to do custom rounding of numbers in Java?

纵然是瞬间 提交于 2019-12-24 03:53:00

问题


Suppose I want to round numbers that have mantissa greater than 0.3 'up' and those below 'down'.

How can I do it in Java?

The only thing that came to my mind was Math.round(), but I can't seem to make it follow a certain rule.


回答1:


Math.floor(x+0.7) should do it.

This should work for an arbitrary mantissa. Just add the offset to the next integer to your value and round down. The rounding is done by floor. Here is what the java API says to floor:

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

This solution is similar to the one from @Thomas Stets, but imho it is easier to understand since rounding is done in only one direction.



来源:https://stackoverflow.com/questions/30976081/how-to-do-custom-rounding-of-numbers-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!