Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number.sign() in javascript

People also ask

How do you check if a number is positive or negative in JS?

The Math. sign() is a builtin function in JavaScript and is used to know the sign of a number, indicating whether the number specified is negative or positive.

Is number negative JavaScript?

The Math. sign() method retuns whether a number is negative, positive or zero. If the number is positive, this method returns 1. If the number is negative, it returns -1.

How do you add a negative sign in JavaScript?

abs() method with a minus, e.g. -Math. abs(10) . When prefixed with a minus, the Math. abs method will always return a negative number.


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

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()