Wonder if there are any nontrivial ways of finding number\'s sign (signum function)?
May be shorter / faster / more elegant solutions than the obvious one
You could bit shift the number and check the Most Significant Bit (MSB). If the MSB is a 1 then the number is negative. If it is 0 then the number is positive (or 0).
More elegant version of fast solution:
var sign = number?number<0?-1:1:0
For people who are interested what is going on with latest browsers, in ES6 version there is a native Math.sign method. You can check the support here.
Basically it returns -1
, 1
, 0
or NaN
Math.sign(3); // 1
Math.sign(-3); // -1
Math.sign('-3'); // -1
Math.sign(0); // 0
Math.sign(-0); // -0
Math.sign(NaN); // NaN
Math.sign('foo'); // NaN
Math.sign(); // NaN
I just was about to ask the same question, but came to a solution before i was finished writing, saw this Question already existed, but didn't saw this solution.
(n >> 31) + (n > 0)
it seems to be faster by adding a ternary though (n >> 31) + (n>0?1:0)
Dividing the number by its absolute value also gives its sign. Using the short-circuiting logical AND operator allows us to special-case 0
so we don't end up dividing by it:
var sign = number && number / Math.abs(number);
var sign = number >> 31 | -number >>> 31;
Superfast if you do not need Infinity and know that the number is an integer, found in openjdk-7 source: java.lang.Integer.signum()