views:

922

answers:

5

I have a variable of type Number, and i like to obtain the sign (if is '-' i like to have -1 and if '+' i like to have 1). So, i made this:

var sign = Math.abs(n) / n;

But, there is any other way? Better than this?

+7  A: 

You'll be in trouble if n == 0... how about this:

var sign = n < 0 ? -1 : 1;
bobwienholt
dang, beat me by 15 seconds :P
davr
thanks, jaja.. i didn't think about n==0. :P
unkiwii
this is a beautiful little piece of code.
matt lohkamp
+2  A: 

You could also do this:

var sign = (n>=0)?1:-1;

Using what's known as the ternary operator.

davr
+5  A: 

That will give you an error if n is zero.

The brute force method:

function sign(num) {
  if(num > 0) {
    return 1;
  } else if(num < 0) {
    return -1;
  } else {
    return 0;
  }
}

Or, for those with a fondness for the conditional operator:

function sign(num) {
  return (num > 0) ? 1 : ((num < 0) ? -1 : 0);
}
Glomek
I like the second approach, it's much cleaner and it deals with the possibility of n being 0.
DL Redden
the sign of 0 is + not 0, so: return (num < 0) ? -1 : 1; Thanks for your answer
unkiwii
A: 

If your number fits in 31 bits then you can use:

var sign = 1 + 2*(n >> 31);

Would be interesting to know if this is any faster!

A: 

Snippet from the code I inherited:

function getSign(number:int):int {
    var tmp:String = new String(number);
    if (tmp.indexOf(0) == '-') {
        return -1;
    }
    return 1;
}

PS: Please don't use this code. It is a joke

Chetan Sastry