Tastybrownies - 3 months ago 15

Java Question

I came to a part in my java program where I need to round up to the nearest hundered and thought that there was probably some way to do it but I guess not. So I seared 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.

- 801->900
- 99->100
- 14->100
- 452->500

Answer

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