Are +0 and -0 the same?

后端 未结 9 1947
花落未央
花落未央 2020-11-22 07:45

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

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

相关标签:
9条回答
  • 2020-11-22 08:13

    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.

    0 讨论(0)
  • 2020-11-22 08:16

    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.

    0 讨论(0)
  • 2020-11-22 08:19

    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
    
    0 讨论(0)
提交回复
热议问题