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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With