Are +0 and -0 the same?

2018-12-31 15:30发布

Reading through the ECMAScript 5.1 specification, +0 and -0 are distinguished.

Why then does +0 === -0 evaluate to true?

标签: javascript
9条回答
像晚风撩人
2楼-- · 2018-12-31 15:59

I just came across an example where +0 and -0 behave very differently indeed:

Math.atan2(0, 0);  //returns 0
Math.atan2(0, -0); //returns Pi

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:

if (x==0) x=0;

or just:

x+=0;

This converts the number to +0 in case it was -0.

查看更多
何处买醉
3楼-- · 2018-12-31 16:07

I'd blame it on the Strict Equality Comparison method ( '===' ). Look at section 4d enter image description here

see 7.2.13 Strict Equality Comparison on the specification

查看更多
后来的你喜欢了谁
4楼-- · 2018-12-31 16:09

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.

查看更多
浅入江南
5楼-- · 2018-12-31 16:11

Answering the original title Are +0 and -0 the same?:

brainslugs83 (in comments of answer by Spudley) pointed out an important case in which +0 and -0 in JS are not the same - implemented as function:

var sign = function(x) {
    return 1 / x === 1 / Math.abs(x);
}

This will, other than the standard Math.sign return the correct sign of +0 and -0.

查看更多
春风洒进眼中
6楼-- · 2018-12-31 16:12

I'll add this as an answer because I overlooked @user113716's comment.

You can test for -0 by doing this:

function isMinusZero(value) {
  return 1/value === -Infinity;
}

isMinusZero(0); // false
isMinusZero(-0); // true
查看更多
呛了眼睛熬了心
7楼-- · 2018-12-31 16:17

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.

查看更多
登录 后发表回答