dot*_*tty 34 javascript integer rounding
干草,我怎样才能将数字四舍五入到最接近的3的倍数?
即
25 would return 27
1 would return 3
0 would return 3
6 would return 6
Run Code Online (Sandbox Code Playgroud)
谢谢
Cam*_*ium 67
if(n > 0)
return Math.ceil(n/3.0) * 3;
else if( n < 0)
return Math.floor(n/3.0) * 3;
else
return 3;
Run Code Online (Sandbox Code Playgroud)
Mak*_*leh 20
这个给你!
Number.prototype.roundTo = function(num) {
var resto = this%num;
if (resto <= (num/2)) {
return this-resto;
} else {
return this+num-resto;
}
}
Run Code Online (Sandbox Code Playgroud)
例子:
y = 236.32;
x = y.roundTo(10);
// results in x = 240
y = 236.32;
x = y.roundTo(5);
// results in x = 235
Run Code Online (Sandbox Code Playgroud)
Iwa*_* B. 16
只是:
3.0*Math.ceil(n/3.0)
Run Code Online (Sandbox Code Playgroud)
?
nis*_*ama 11
正如对已接受答案的评论中所述,您可以使用:
Math.ceil(x/3)*3
Run Code Online (Sandbox Code Playgroud)
(即使它在x0 时不返回3 ,因为这可能是OP的错误.)
在此之前发布的九个答案中(尚未删除或者没有得到如此低的分数以至于所有用户都看不到),只有Dean Nicholson的答案(除了重要性不足的问题)和beauburrier是正确的.接受的答案给出了负数的错误结果,它为0添加了一个例外,以说明OP可能出现的错误.另外两个答案将数字四舍五入到最接近的倍数而不是总是向上舍入,一个给出负数的错误结果,另外三个给出正数的错误结果.
小智 9
我在psuedocode中回答这个问题,因为我主要在SystemVerilog和Vera(ASIC HDL)中编程.%表示模量函数.
round_number_up_to_nearest_divisor = number + ((divisor - (number % divisor)) % divisor)
Run Code Online (Sandbox Code Playgroud)
这在任何情况下都适用.
数的模数计算余数,从除数中减去得到达到下一个除数倍所需的数,然后发生"魔术".你会认为单模数函数足够好,但是在数是除数的精确倍数的情况下,它会计算一个额外的倍数.即,24将返回27.附加模数通过使加法0来防止这种情况.
此函数将向上舍入到您提供的任何因子的最接近倍数.它不会向上舍入0或已经是倍数的数字.
round_up = function(x,factor){ return x - (x%factor) + (x%factor>0 && factor);}
round_up(25,3)
27
round up(1,3)
3
round_up(0,3)
0
round_up(6,3)
6
Run Code Online (Sandbox Code Playgroud)
0的行为不是你要求的,但这种方式似乎更加一致和有用.如果您确实想要向上舍入0,则以下函数会执行此操作:
round_up = function(x,factor){ return x - (x%factor) + ( (x%factor>0 || x==0) && factor);}
round_up(25,3)
27
round up(1,3)
3
round_up(0,3)
3
round_up(6,3)
6
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35405 次 |
| 最近记录: |