java - Rounding Up To The Nearest Hundred -
i came part in java program need round nearest hundred , thought there way guess not. searched net examples or answers , i've yet find since examples appear to nearest hundred. want , round up. maybe there's simple solution i'm overlooking. have tried math.ceil
, other functions have not found answer of yet. if me issue appreciate it.
if number 203, want result rounded 300. point.
- 801->900
- 99->100
- 14->100
- 452->500
take advantage of integer division, truncates decimal portion of quotient. make it's rounding up, add 99 first.
int rounded = ((num + 99) / 100 ) * 100;
examples:
801: ((801 + 99) / 100) * 100 → 900 / 100 * 100 → 9 * 100 = 900 99 : ((99 + 99) / 100) * 100 → 198 / 100 * 100 → 1 * 100 = 100 14 : ((14 + 99) / 100) * 100 → 113 / 100 * 100 → 1 * 100 = 100 452: ((452 + 99) / 100) * 100 → 551 / 100 * 100 → 5 * 100 = 500 203: ((203 + 99) / 100) * 100 → 302 / 100 * 100 → 3 * 100 = 300 200: ((200 + 99) / 100) * 100 → 299 / 100 * 100 → 2 * 100 = 200
relevant java language specification quote, section 15.17.2:
integer division rounds toward 0. is, quotient produced operands n , d integers after binary numeric promotion (§5.6.2) integer value q magnitude large possible while satisfying |d · q| ≤ |n|.
Comments
Post a Comment