Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do custom rounding of numbers in Java?

Tags:

java

rounding

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.

like image 238
Hadi Satrio Avatar asked Sep 03 '25 17:09

Hadi Satrio


1 Answers

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.

like image 118
NaN Avatar answered Sep 05 '25 06:09

NaN