-0 in JavaScript after using Math.round? What is -0?

I just wanted to create a random integer in the range <-1,1>, that is -1, 0 or 1. I think this code nails it:

Math.round(Math.random()*2-1)

But I get another value besides -1, 0 and 1. I am not sure what this should be:

image description

Now I do not think that this is an implementation error, but if so, I use Firefox 41, and the same thing happened in Google Chrome 39. When I tried to record -0in the console, it looked like -0but -0, converted to String, it displays like "0". What is it? Can I use it for something, for example, for some interesting software hacks and workarounds? Could this cause some errors if I don't just ignore it?

+4
source share
3 answers

Two zeros

Since JavaScripts numbers are stored and signed separately, each non-negative number has a negative result, including 0. The rationale for this is that whenever you digitally represent a number, it can become so small that it is indistinguishable from 0, therefore that the encoding is not accurate enough to represent the difference. Then the signed zero allows you to write down "from which direction" you approached zero; that is, what sign the number had before it was considered zero.

from here


More technical materials if you are interested.

-0 +0 1985 IEEE IEEE 754. , , .

  • : , ( ), " " (NaNs)
  • : ( ),
  • : ,
  • : : (, , ..).
+5

ECMAScript : +0 -0.

:

+0 == -0          // true (Equality comparison)
+0 === -0         // true (StrictEquality comparison)
[+0].includes(-0) // true (SameValueZero comparison)

:

Object.is(+0, -0) // false (SameValue comparison)

, . ,

1 / +0 === +Infinity
1 / -0 === -Infinity

-0, Math.round :

x 0, -0,5, -0.

, -2 31 2 31 -1, +0, -0, , :

-1 | 0 // -1
-0 | 0 // +0
+0 | 0 // +0
+1 | 0 // +1

-1 Math.round:

Math.round(Math.random()*2) - 1

Math.round .

Math.floor(Math.random()*3) - 1
+3

Math.round :

x 0, -0,5, -0.

Math.random 0 () 1 (), .

+2

Source: https://habr.com/ru/post/1612170/


All Articles