Number.sign() in javascript
More elegant version of fast solution:
var sign = number?number<0?-1: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);
The function you're looking for is called signum, and the best way to implement it is:
function sgn(x) {
return (x > 0) - (x < 0);
}
Should this not support JavaScript’s (ECMAScript’s) signed zeroes? It seems to work when returning x rather than 0 in the “megafast” function:
function sign(x) {
return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? x : NaN : NaN;
}
This makes it compatible with a draft of ECMAScript’s Math.sign (MDN):
Returns the sign of the x, indicating whether x is positive, negative or zero.
- If x is NaN, the result is NaN.
- If x is −0, the result is −0.
- If x is +0, the result is +0.
- If x is negative and not −0, the result is −1.
- If x is positive and not +0, the result is +1.
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