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?
From stackoverflow
unkiwii
-
You'll be in trouble if n == 0... how about this:
var sign = n < 0 ? -1 : 1;davr : dang, beat me by 15 seconds :Punkiwii : thanks, jaja.. i didn't think about n==0. :Pmatt lohkamp : this is a beautiful little piece of code.From bobwienholt -
You could also do this:
var sign = (n>=0)?1:-1;Using what's known as the ternary operator.
From davr -
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); }DL Redden : I like the second approach, it's much cleaner and it deals with the possibility of n being 0.unkiwii : the sign of 0 is + not 0, so: return (num < 0) ? -1 : 1; Thanks for your answerFrom Glomek -
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!
-
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
From Chetan Sastry
0 comments:
Post a Comment