gpt4 book ai didi

javascript - 为什么 Math.round(-0.2) 返回 -0?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:57:00 25 4
gpt4 key购买 nike

我今天在使用 Javascript 时遇到了一个小问题:

我有一组值,例如:

US         11.3123
Brazil -0.2291
UK 0.4501

我想显示没有小数位,四舍五入的值,所以它会显示为:

US         11
Brazil -0
UK 0

所以,问题是巴西显示的是“-0”而不是“0”。

好吧,我可以轻松解决:

html += '<tr><td>' + arr[i].Country + '</td>' +
'<td>' + d3.format(arr[i].Value || 0, 0) + '</td></tr>';

为什么 Math.round 返回 -0 而不是 0?

更新

我正在使用 D3.js format function ,它将 JavaScript 行为传输到输出。但是,由于在控制台中,我仍然有这个疑问:

Math.round(-0.02)
> -0

最佳答案

来自 ecmascript 定义:http://es5.github.io/#x15.8.2.15

If x is NaN, the result is NaN.
If x is +0, the result is +0.
If x is −0, the result is −0.
If x is +∞, the result is +∞.
If x is −∞, the result is −∞.
If x is greater than 0 but less than 0.5, the result is +0.
If x is less than 0 but greater than or equal to -0.5, the result is −0.

NOTE 2 The value of Math.round(x) is the same as the value of Math.floor(x+0.5), except when x is −0 or is less than 0 but greater than or equal to -0.5; for these cases Math.round(x) returns −0, but Math.floor(x+0.5) returns +0.

关于javascript - 为什么 Math.round(-0.2) 返回 -0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22649648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com