r/javahelp • u/zetayshow • Sep 02 '20
Unsolved Math.round() rounding properties
Good morning Reddit, So I’m using math round to round some ints. Everything is fine except that if I try to round 445 it rounds to 450. This behavior is fine and acceptable but I’m trying to round to the hundredth digit. This means I want 445 to become 500 from going 445 to 450 and then 500. Is this possible with math round and anyone knows how? I’ve already been on google and stackoverflow but can’t find nothing that worked...
Thanks in advance!
9
u/Roachmeister Java Dev Sep 02 '20
I'm very confused by your question because this is not how round() works. It doesn't round ints. It takes a fractional value and rounds to the nearest integer. For example, 4.5 -> 5.0, or 4.45 -> 4.0. I'm not aware of any way to make it round 445 to 450, unless you first divided by 10, i.e. 44.5 rounds to 45.0.
2
2
u/DJDavio Sep 02 '20
You don't actually need Math.round, just do ((number + 50) / 100) * 100. By adding 50 you do sort of a manual round. Each number ending in something smaller than 50, such as 449, will not exceed the next hundred. In this case it will be 499 which divided by 100 gives 4 (int division cuts the remainder off) and multiplying again gives 400.
1
1
u/bhaskargupta98 Sep 02 '20
You can use Serialiser or properties to define the order to which it should round off As you are already using inbuilt libraries then why to add slightest of mathematics
11
u/sinistergroupon Sep 02 '20
As stated in the other comment round just does the decimal digits. If you want to round at the hundred level then divide by 100, run it through round then multiply by 100.