Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding Up To The Nearest Hundred

I came to a part in my java program where I need to round up to the nearest hundred and thought that there was probably some way to do it but I guess not. So I searched the net for examples or any answers and I've yet to find any since all examples appear to be to the nearest hundred. I just want to do this and round UP. Maybe there's some simple solution that I'm overlooking. I have tried Math.ceil and other functions but have not found an answer as of yet. If anyone could help me with this issue I would greatly appreciate it.

If my number is 203, I want the result rounded to be 300. You get the point.

  1. 801->900
  2. 99->100
  3. 14->100
  4. 452->500
like image 647
Tastybrownies Avatar asked Aug 23 '13 16:08

Tastybrownies


People also ask

What is 2345 rounded to the nearest hundreds?

Example: Round to the nearest hundred: 2345 would be 2300.

What does 350 round to the nearest hundred?

350 rounded to the nearest 100 is rounded up to 400.


1 Answers

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|.

like image 55
rgettman Avatar answered Oct 05 '22 13:10

rgettman