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?
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?
You'll be in trouble if n == 0... how about this:
var sign = n < 0 ? -1 : 1;
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);
}
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