如何在Java中将数字向下舍入到最接近的20的倍数?

5
请记住,我只想向下取最接近20的倍数,不会向上取整。
  • 22 --> 20
  • 45 --> 40
  • 69.5 --> 60
  • 60 --> 60
非常感谢!

5
你到目前为止尝试了什么?SO不会为你编写代码或在你没有付出努力的情况下分享想法。 - SMA
5个回答

13

一种解决方案是从初始值中减去模20的结果(即除以20后的余数)。类似于以下内容:

double[] in = { 22, 45, 69.5, 60 };
for (double d : in) {
    int v = (int) d;
    v -= v % 20;
    System.out.printf("%.1f --> %d%n", d, v);
}

输出结果为

22.0 --> 20
45.0 --> 40
69.5 --> 60
60.0 --> 60

12
public static Integer round20(Integer b){
        return b - (b%20);
    }

4
你可以除以20,四舍五入(使用Math.floor),然后再乘以20。

3
你正在寻找求余运算。来自维基百科的定义:

在计算机中,求余运算是指将一个数除以另一个数后得到余数的运算。

因此,您可以这样写:
int unrounded = 66;
int rounded = unrounded - (unrounded % 20);

作为一种方法:

public static int moduloFloor(int toRound, int modulo) {
    return toRound - (toRound % modulo);
}

0

你想知道提供的数字中有多少个20。假设x是你的输入,请尝试以下方法:

Math.floor(x / 20) * 20

3
与提供的 x - (x % 20) 的解答相比,这种方法更昂贵(减法比乘法更便宜/更快)。此外,使用 Math.floor() 函数速度较慢。 - frasnian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接