I’m searching for an efficient way to check if two numbers have the same sign.
Basically I’m searching for a more elegant way than this:
var n1 = 1;
var n2 = -1;
( (n1 > 0 && n2 > 0) || (n1<0 && n2 < 0) )? console.log("equal sign"):console.log("different sign");
A solution with bitwise operators would be fine too.
Fewer characters of code, but might underflow for very small numbers:
Note: As @tsh correctly mentioned, an overflow with an intermediate result of
Infinityor-Infinitydoes work. But an underflow with an intermediate result of+0or-0will fail, because+0is not bigger than0.or without underflow, but slightly larger: