views:

56

answers:

3

i'd like to negate a number and would like to know if there's a built in method that will convert a negative number to a positive OR a positive into a negative, depending on the number.

i know about Math.abs(), but that only seems to convert negative into positive. is there a method that will do both?

+4  A: 
var mynum:Number = 5;
mynum = -mynum;

Other options include:

  • mynum*=-1;
  • mynum = 0-mynum
Cam
+2  A: 

Isn't this as simple as multiplying by -1?

JB King
ah! so it is! LOL. i guess that's a simple as any built in method could be. thanks :)
TheDarkInI1978
Yeah you were totally overthinking it :)
Cam
but taking it as "-p" is better than doing "-1*p" for real; -p can be compiled into a single instruction that negates the variable (disregarding loading/storing instructions), while -1*p can get compiled into: load a constant, multiply the constant (-1) by p: 1 instr more and moreover multiplying can be slower, while negating is faster. (At least I hope that any reasonable VM has the negate instr on numbers both float and integer!)
ShinTakezou
Is it possible for some compilers to convert a "-1*" to the same as a unary negation operation? Just a question I'd toss out there.
JB King
@JB King: Yes, any arithmetic operation to negate a number will be optomized by the compiler to be as fast as possible (flipping the sign bit).
Cam
A: 

Do you need a method? Unary minus should do the trick as in many other languages! If p > 0, -p < 0 and viceversa as we learned at school.

ShinTakezou