Round Up to the Nearest Hundred in Java – 在Java中四舍五入到最近的一百位数

最后修改: 2018年 9月 19日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

例如:
99变成100

200.2变成300

400变成400

2. Implementation

2.实施

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.

首先,我们要对输入参数调用Math.ceil()Math.ceil()返回大于或等于参数的最小整数。例如,如果输入是200.2Math.ceil()将返回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.

接下来,我们在结果上加上99,然后除以100。我们利用整数除法的优势来截断商的小数部分。最后,我们将商乘以100,得到我们想要的输出。

Here is our implementation:

以下是我们的实现。

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

3. Testing

3.测试

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

4.总结

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.

像往常一样,完整的代码可以在GitHub上找到