Why Math.round (-0.2) returns "-0" instead of "0"

8

I had a problem with Javascript today that I will describe:

I have a collection of values, for example:

US         11.3123
Brazil     -0.2291
UK          0.4501

I want to display the values without the decimal places, rounding up, and the result is this:

US         11
Brazil     -0
UK          0

The problem is that "Brazil" has a value of "-0" instead of "0".

I can even fix it easily:

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

But why does Javascript show negative sign value?

Update

I'm using d3, and it's broadcasting Javascript behavior instead of returning the unsigned 0 as pure JS does.

But my question still continues, because in the console I type Math.round (-0.02) and it is returned -0.

    
asked by anonymous 26.03.2014 / 02:31

1 answer

11

This is not a feature of JavaScript alone, but rather of how floating point works. In this representation, there are two values for zero : +0 and -0 . Implementations are required to treat them as equals (in comparisons), but are still represented by two different values.

If your application is not interested in the two values (as in fact, in most domains only one zero is concerned) then your way of correcting it (doing "or" with zero) is ok. Just be careful with NaN ( not a number ) because it will also be converted to zero by this logic.

    
26.03.2014 / 02:44