我今天遇到了一个小问题:
我有一个值集合,例如:
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>';
为什么数学。四舍五入返回-0而不是0?
我使用D3.js格式函数,它将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.
注2Math.round(x)的值与的值相同Math.floor(x+0.5),除非x为- 0或小于0但大于0小于或等于-0.5;对于这些情况,Math.round(x)返回−0,但是Math.floor(x+0.5)返回+0。
问题是巴西显示的是"-0"而不是"0"。
不能。虽然@JoeFrambach和@Amdan解释了这一点,以及为什么JS区分+0和-0,但这不能从你的代码输出(除非你的JS引擎有缺陷)。引用EcmaScript§9.8.1 ToString
应用于Number
类型:
2。如果[数字]是
+0
或−0
,返回String"0"
无负号:
Math.round(-0.2) + '' == "0"
Math.round( 0.2) + '' == "0"