How to do custom rounding of numbers in Java?

2.2k Views Asked by At

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

There are 1 best solutions below

0
On BEST ANSWER

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.