I had a little problem with Javascript today:
I have a collection of values, for example:
US 11.3123
Brazil -0.2291
UK 0.4501
I want to display with no decimal places, rounding values, so it will be displayed as:
US 11
Brazil -0
UK 0
So, the problem is that Brazil is showing "-0" instead of "0".
Well, I can workaround easily:
html += '<tr><td>' + arr[i].Country + '</td>' +
'<td>' + d3.format(arr[i].Value || 0, 0) + '</td></tr>';
Why does Math.round return -0 instead of 0?
Update
I'm using D3.js format function, which transmits JavaScript behavior to output. But still, I have this doubt due to the fact that in console:
Math.round(-0.02)
> -0
From the ecmascript definition: 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.
the problem is that Brazil is showing "-0" instead of "0".
It must not. While @JoeFrambach and @Amdan explained that and why JS does distinguish between +0 and -0, this must not be output from your code (unless your JS engine is flawed). To cite EcmaScript §9.8.1 ToString
Applied to the Number
Type:
2. If [the number] is
+0
or−0
, return the String"0"
No minus sign:
Math.round(-0.2) + '' == "0"
Math.round( 0.2) + '' == "0"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With