Why Math.round(-0.2) returns "-0" and not "0"

Asked

Viewed 135 times

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 show the values without the decimal places, round, and the result is this:

US         11
Brazil     -0
UK          0

The problem is that "Brazil" has the value "-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 Javascript shows the value with negative sign?


Updating

I’m using D3, and it’s transmitting Javascript behavior instead of returning 0 without signal as pure JS does.

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

  • 2

    Are you sure there’s nothing else in between? My tests always returned "0" and not "-0".

  • 3

    @Filipe What browser are you using? In Chrome, when printing Math.round(-0.2) on the console got -0.

  • I used the Chrome

1 answer

12


This is not just a Javascript feature, but the way floating point works. In this representation, there are two values for zero: +0 and -0. Implementations are required to treat them as equal (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 it only interests a zero) then your way of correcting it (doing "or" with zero) is ok. Just be careful with the NaN (not a number), because it will also be converted to zero according to this logic.

  • thank you very much for the explanation and reminder of NaN! ( actually before the array, has a null, NaN and empty string for "0" - is part of the program specification :)).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.