Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiating +0 and -0

Tags:

javascript

It turns out +0 === -0 evaluates to true despite +0 and -0 being different entities. So, how do you differentiate +0 from -0?

There is a hack:

if (1 / myZero > 0) {
   // myZero is +0
} else {
   // myZero is -0
}

Can I do better?

like image 806
Randomblue Avatar asked Aug 28 '11 20:08

Randomblue


6 Answers

In ECMAScript 6 Object.is behaves like === except that it distinguishes positive and negative zeroes, and Object.is(NaN, NaN) evaluates to true. (See here for a writeup.)

Chrome 24 supports Object.is.

like image 85
Randomblue Avatar answered Nov 18 '22 00:11

Randomblue


This is still some kind of hack, but a look at the specs suggests this:

Math.atan2(0, -0) === Math.PI // true
Math.atan2(0,  0) === 0       // true
like image 29
pimvdb Avatar answered Nov 17 '22 23:11

pimvdb


According to David Flanagan's book, p. 34, dividing 1 by your zero will produce the corresponding infinity, which can then be used in an equality check:

1 / 0
> Infinity
1 / -0
> -Infinity

And here's the behavior of the equality comparisons of infinities:

Infinity === -Infinity
> false
Infinity === Infinity
> true
-Infinity === Infinity
> false
-Infinity === -Infinity
> true
like image 44
Matt Fenwick Avatar answered Nov 17 '22 23:11

Matt Fenwick


This returns +0:

-0 + 0

This doesn't help to differenciate -0 and +0, but this helps in ensuring that some value is not -0.

1 / -0       => -Infinity  
1 / (-0 + 0) => Infinity
like image 37
Arnaud Le Blanc Avatar answered Nov 17 '22 23:11

Arnaud Le Blanc


To check the negative zero, here is one simple solution.

function isNegativeZero(n) {
    n = Number( n );
    return (n === 0) && (1 / n === -Infinity);
}
like image 4
zangw Avatar answered Nov 18 '22 01:11

zangw


As people seem stumped as to what the practical need for this would be: here is my use case...

I needed a solution to sort the columns of a table by their index. Click the <th> and invoke the sorter with [ordinal] for ascending and -[ordinal] for descending. The first column would give -0 for descending or 0 for ascending.

So I need to differentiate between +0 and -0 and ended up here. The solution that worked for me is in the comment by @Šime Vidas, but is hidden away somewhat.

[ section removed - see comments below ]

like image 3
Roy Prins Avatar answered Nov 18 '22 00:11

Roy Prins