Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain the sign of a Number in ActionScript 3.0?

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?

like image 395
Lucas Gabriel Sánchez Avatar asked Nov 28 '22 12:11

Lucas Gabriel Sánchez


2 Answers

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

var sign = n < 0 ? -1 : 1;
like image 89
bobwienholt Avatar answered Jan 29 '23 06:01

bobwienholt


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);
}
like image 37
Andru Luvisi Avatar answered Jan 29 '23 08:01

Andru Luvisi