1. Overview

In this quick tutorial, we’ll illustrate how to round up a given number to the nearest hundred.

For example:
99 becomes 100
200.2 becomes 300
400 becomes 400

2. Implementation

First, we’re going to call Math.ceil() on the input parameter. Math.ceil() returns the smallest integer that is greater than or equal to the argument. For example, if the input is 200.2 Math.ceil() would return 201.

Next, we add 99 to the result and dividing by 100. We are taking advantage of Integer division to truncate the decimal portion of the quotient. Finally, we are multiplying the quotient by 100 to get our desired output.

Here is our implementation:

static long round(double input) {
    long i = (long) Math.ceil(input);
    return ((i + 99) / 100) * 100;
};

3. Testing

Let’s test the implementation:

@Test
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
    assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
    assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
    assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
}

4. Conclusion

In this quick article, we’ve shown how to round a number up to the nearest hundred.

As usual, the complete code is available on the GitHub.