I am using MomentJS to calculate the difference between two times. The weird thing is about this library is the difference between today and today is 0. The difference between today and tomorrow is -0.
My question is, how do I differentiate between 0 and -0. It seems JavaScript treats them the same.
So for example if I write the following code:
if (tomorrow === -0)
console.log('It is tomorrow!');
else if (tomorrow === 0)
console.log('It is today!');
Here's an example on JSFiddle as to how it handles the returned values (I am in Australia so depending on where you are in the word you may have to adjust the today and tomorrow dates)
Signed zero is zero with an associated sign. In ordinary arithmetic, the number 0 does not have a sign, so that −0, +0 and 0 are identical.
The name for this is Signed Zero. It turns out the reason that JavaScript has -0 is because it is a part of the IEEE 754 floating-point specification. Two zeroes are also present in other languages like Ruby as well.
In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.
There's no such thing as negative zero. For a binary integer, setting the sign bit to 1 and all other bits to zero, you get the smallest negative value for that integer size. (Assuming signed numbers.) Negative zero is actually used in mathematical analysis, especially in limit calculations.
1/val > 0
will do what you want. Returns true
for positive and false
for negative.
This works because 1/-0
returns negative infinity, and 1/0
returns positive infinity, which are then comparable. You could also do something like 1/val == Infinity
.
As pointed out in this Stack Overflow question (and in the comments), in JavaScript +0 === -0
indeed evaluates to true
by design.
You can use Infinity
/-Infinity
to see a difference (technically, +0
/-0
might not be the only numbers to produce infinite values, so I left the additional check in):
var positiveZero = +0; var negativeZero = -0; console.log(positiveZero === 0 && 1/positiveZero === Infinity); // true console.log(positiveZero === 0 && 1/positiveZero === -Infinity); // false console.log(negativeZero === 0 && 1/negativeZero === Infinity); // false console.log(negativeZero === 0 && 1/negativeZero === -Infinity); // true
JSFiddle
See also this blog post for more details and yet another solution with ECMAScript 5:
function isNegative0(x) { if (x!==0) return false; var obj=Object.freeze({z:-0}); try { Object.defineProperty(obj,'z',{value:x}); } catch (e) {return false}; return true; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With