Rounding Up To The Nearest Hundred
Here is an algorithm which I belive works for any "multiple of" case. Let me know what you think.
int round (int number,int multiple){
int result = multiple;
//If not already multiple of given number
if (number % multiple != 0){
int division = (number / multiple)+1;
result = division * multiple;
}
return result;
}
Take advantage of integer division, which truncates the decimal portion of the quotient. To make it look like 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. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|.