tags:

views:

1713

answers:

7

Does such function exist? I created my own but would like to use an official one:

private function opposite(number:Number):Number
     {
      if (number < 0)
      {
       number = Math.abs(number);
      }
      else
      {
       number = -(number);
      }
      return number;
     }

So, -5 becomes 5 and 3 becomes -3.

Edit: Forgive me for being stupid. I'm human. :)

+47  A: 

yes it does...

return num*-1;

or simply

return -num;
John T
The only correct answer, as far as I'm concerned. No more answers needed.
peSHIr
As long as this is a compiled language where the compiler can optimize that multiplication away.
Michael Myers
Not sure why you got so many upvotes with this. Hello!?!? If only for clarity for the next programmer to see it, "return -num;"
Emtucifor
@Emtucifor, multiplication is still performed either way. This answer is not wrong.
John T
@John T, not true if the number is stored in two's compliment. The value of -num can be computed by flipping all the bits and adding one (~num + 1) which is significantly faster than multiplication.
Kevin Loney
@Kevin, yes but when using a compiled language, both will be compiled to a single NEGL instruction performed on the register so it does not matter. When compiled there is no difference as the multiplication is removed. My answer is not necessarily wrong, just 2 characters longer than needed. Downvotes are for incorrect answers or bad information, this is neither.
John T
I call this bad information because "compiler-correctness" is not the only criterion for good code. I'll remove my downvote, but in my shop I would call this answer from a developer wrong and would make him change it.
Emtucifor
If a developer in your shop does not understand how that piece of code works I fear for your shop's well being and success.
John T
+15  A: 

Simply putting a negative sign in front of the variable or number will do the trick, even if it's already negative:

-(-5) => 5
$foo = 3; -$foo => -3
James Skidmore
+22  A: 

How about:

return -(number)

as -(-5) == 5.

andri
+5  A: 

This a trick question? why a function? just do number * -1, multiply with -1 that is.

Joakim Elofsson
+2  A: 

try something like number = number * (-1)

Roman
+2  A: 

You could use

number *= -1;

3 becomes -3 and -5 becomes 5 :)

Burkhard
A: 

number *= -1; or number = number * (-1);

DeeptaPatel1980