Skip to content
Advertisement

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

Advertisement

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.

JavaScript

Examples:

JavaScript

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

Advertisement