将数字四舍五入到特定的倍数 [英] Rounding numbers to specific multiples
问题描述
我怎样才能在Java中找到特定的倍数?
在excel中有 mround
函数,它可以很容易地四舍五入到指定的倍数,如下所示:
How can I round to a specific multiple in Java?
In excel there is the mround
function which allows for easy rounding to a specified multiple like so:
mRound(variable,multiple)
所以<$ c $如果 x = 7.9
和 9
code> 6 if x = 7.2
。
so mRound(x,3)
would return 9
if x = 7.9
and 6
if x = 7.2
.
所有四舍五入我迄今为止发现的函数总是四舍五入到最接近的整数或指定的小数位数,但我希望能够更改每个变量的倍数。有没有人知道哪种功能最适合这种情况?
All of the rounding functions I have found so far always round to the nearest whole number or to a specified number of decimal places but I want to be able to change the multiple for each variable. Does anyone know what function would be best for this situation?
推荐答案
只需将数字除以数字,再乘以数字即可。
Just divide by the number, round, and multiply by the number.
double mRound(double value, double factor) {
return Math.round(value / factor) * factor;
}
这篇关于将数字四舍五入到特定的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!