How to get number sign in ActionScript 3.0?

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

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

But is there any other way? Better than that?

+4
source share
7 answers

You will have problems if n == 0 ... how about this:

 var sign = n < 0 ? -1 : 1; 
+13
source

This will give you an error if n is zero.

Brute Force Method:

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

Or for those who are attached to the conditional statement:

 function sign(num) { return (num > 0) ? 1 : ((num < 0) ? -1 : 0); } 
+8
source

You can also do this:

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

Using the so-called ternary operator .

+2
source

I use this:

 return (number < 0 && -1) || 1; 
+1
source

If your number matches 31 bits, you can use:

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

It would be interesting to know if it is faster!

0
source

Code snippet I inherited:

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

PS: Please do not use this code. This is a joke

0
source

// n = your number // nSign = sign of your number

nSign = Math.round (Math.sin (n) * - 1);

/ * Math.sin returns a number from -1 to 1. You must round it to get a non-DEC number. This number will be the opposite of what your number is. Multiply it by -1 * /

// or you could just do it

Math.round (Math.sin (/ n /) * - 1)

0
source

Source: https://habr.com/ru/post/1277444/


All Articles