问题描述
我处于JavaScript函数产生数字的情况,例如 2.5
。我想将这5个数字四舍五入为 2
,而不是 Math.round
的结果,在这种情况下,总是四舍五入(忽略偶数奇数规则),产生2。除了四舍五入之前从数字中减去0.01之外,还有其他更优雅的方法吗?谢谢。
I am in a situation where a JavaScript function produces numbers, such as 2.5
. I want to have these point five numbers rounded down to 2
, rather than the result of Math.round
, which will always round up in such cases (ignoring the even odd rule), producing 2. Is there any more elegant way of doing this than subtracting 0.01 from the number before rounding? Thanks.
推荐答案
只需将输入和输出取反到 Math.round
:
Just negate the input and the output to Math.round
:
var result = -Math.round(-num);
详细信息:JavaScript的 Math.round
具有不寻常的性质,可以将中间情况舍入为正无穷大,无论它们是正数还是负数。因此,例如 2.5
将舍入为 3.0
,但是 -2.5
将舍入为 -2.0
。这是一种不常见的舍入模式:将中途情况的舍入取整为零或更少(因此 -2.5
会舍入为 -3.0
)或最接近的偶数。
In more detail: JavaScript's Math.round
has the unusual property that it rounds halfway cases towards positive infinity, regardless of whether they're positive or negative. So for example 2.5
will round to 3.0
, but -2.5
will round to -2.0
. This is an uncommon rounding mode: it's much more common to round halfway cases either away from zero (so -2.5
would round to -3.0
), or to the nearest even integer.
但是,它确实具有很好的属性,可以很容易地将其适应于负负无穷大的中途情况:如果这就是您想要的,那么您要做的就是对输入和输出进行求反:
However, it does have the nice property that it's trivial to adapt it to round halfway cases towards negative infinity instead: if that's what you want, then all you have to do is negate both the input and the output:
示例:
function RoundHalfDown(num) {
return -Math.round(-num);
}
document.write("1.5 rounds to ", RoundHalfDown(1.5), "<br>");
document.write("2.5 rounds to ", RoundHalfDown(2.5), "<br>");
document.write("2.4 rounds to ", RoundHalfDown(2.4), "<br>");
document.write("2.6 rounds to ", RoundHalfDown(2.6), "<br>");
document.write("-2.5 rounds to ", RoundHalfDown(-2.5), "<br>");
这篇关于JavaScript:四舍五入为5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!