Reading through the ECMAScript 5.1 specification, +0
and -0
are distinguished.
Why then does +0 === -0
evaluate to true
?
Reading through the ECMAScript 5.1 specification, +0
and -0
are distinguished.
Why then does +0 === -0
evaluate to true
?
I just came across an example where +0 and -0 behave very differently indeed:
Be careful: even when using Math.round on a negative number like -0.0001, it will actually be -0 and can screw up some subsequent calculations as shown above.
Quick and dirty way to fix this is to do smth like:
or just:
This converts the number to +0 in case it was -0.
I'd blame it on the Strict Equality Comparison method ( '===' ). Look at section 4d
see 7.2.13 Strict Equality Comparison on the specification
Wikipedia has a good article to explain this phenomenon: http://en.wikipedia.org/wiki/Signed_zero
In brief, it both +0 and -0 are defined in the IEEE floating point specifications. Both of them are technically distinct from 0 without a sign, which is an integer, but in practice they all evaluate to zero, so the distinction can be ignored for all practical purposes.
Answering the original title
Are +0 and -0 the same?
:brainslugs83
(in comments of answer bySpudley
) pointed out an important case in which +0 and -0 in JS are not the same - implemented as function:This will, other than the standard
Math.sign
return the correct sign of +0 and -0.I'll add this as an answer because I overlooked @user113716's comment.
You can test for -0 by doing this:
In the IEEE 754 standard used to represent the Number type in JavaScript, the sign is represented by a bit (a 1 indicates a negative number).
As a result, there exists both a negative and a positive value for each representable number, including
0
.This is why both
-0
and+0
exist.