One thing that I always took for granted until last week was testing for negative numbers. What I mean is that I had no clue that -0
is actually different from 0
. Interestingly enough when using strict equality to test the two values they still appear to be equal but they are in fact different. For this reason, I decided to write the following function:
function isNegative(n) {
return ((n = +n) || 1 / n) < 0;
}
[/code]
I admit that this function probably isn't that useful because I haven't thought of one time when you really need to know if a value is -0
or 0
, but just in case I or anyone else in the future does need a way to differentiate, the above function should do the trick. The following are some examples of calling the function:
[code language=javascript]
var a = isNegative(-Infinity); // true
var b = isNegative(-12); // true
var c = isNegative(-0); // true
var d = isNegative(0); // false
var e = isNegative(34); // false
var f = isNegative(Infinity); // false
var g = isNegative("Hello"); // NaN -> false
var h = isNegative(undefined); // NaN -> false
var i = isNegative(null); // 0 -> false
var j = isNegative(-null); // -0 -> true
var k = isNegative("-5"); // -5 -> true
var l = isNegative("-0"); // -0 -> true
var m = isNegative("0"); // 0 -> false
var n = isNegative("6"); // 6 -> false
var o = isNegative(""); // 0 -> false
I'm guessing this is more than you ever wanted to know about negative numbers so I will end the post here. 😎
5 Comments
roelof berkepeis · February 25, 2014 at 9:41 PM
nice completeness, and .. just in time! 🙂
Ben · September 2, 2015 at 5:03 PM
Thanks Chris! This was actually useful as moment.js returns negative zeroes and positive zeroes for different occasions so this function works great to figure out which one is which!
Chris · April 27, 2016 at 1:29 PM
Perfect! thanks!
Nathaniel · November 9, 2017 at 11:27 PM
How about an array accessor where you want +0 –> +n to match array[n] and -0 –> -n to match array[array.length – Math.abs(n)].
Javascript Math Object Methods - Negatives To Zero - Programming Questions And Solutions Blog · March 1, 2023 at 7:06 AM
[…] Source: http://cwestblog.com/2014/02/25/javascript-testing-for-negative-zero/ […]