本文介绍了将数字四舍五入为最接近的5的倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有谁知道如何将数字四舍五入到最接近的5的倍数?我发现了一个算法将它四舍五入到最接近的10的倍数,但我找不到这个。
Does anyone know how to round up a number to its nearest multiple of 5? I found an algorithm to round it to the nearest multiple of 10 but I can't find this one.
这是10个。
double number = Math.round((len + 5)/ 10.0) * 10.0;推荐答案
int roundUp(int n) { return (n + 4) / 5 * 5; }
注意 - YankeeWhiskey的答案是四舍五入到最接近的倍数,这是四舍五入。如果您需要修改负数,则需要进行修改。请注意,整数除法后跟相同数字的整数乘法是向下舍入的方式。
Note - YankeeWhiskey's answer is rounding to the closest multiple, this is rounding up. Needs a modification if you need it to work for negative numbers. Note that integer division followed by integer multiplication of the same number is the way to round down.
更多推荐
将数字四舍五入为最接近的5的倍数
发布评论