views:

191

answers:

5

I have a variable that will sometimes be negative and sometimes positive.

Before I use it I need to make it positive. How can I accomplish this?

+2  A: 
if (myvar < 0) {
  myvar = -myvar;
}

or

myvar = Math.abs(myvar);
kgiannakakis
So doing -myvar to a value like -900 makes it negative of -900 or 900?
ian
A negative negative is positive. So -(-900) == 900.
bigmattyh
Yes, since two negatives make a positive. I would use Math.abs() though
T B
@ian - yes. it does.
marcc
In programming, two wrongs *do* make a right! :)
Carl Smotricz
Er, that's math, not programming.
jprete
+9  A: 

Use the Math.abs method

http://www.w3schools.com/jsref/jsref%5Fabs.asp

There is a comment below about using negation (thanks Kelly for making me think about that), and it is slightly faster vs the Math.abs over a large amount of conversions if you make a local reference to the Math.abs function (without the local reference Math.abs is much slower). Look at the answer to this question for more detail. Over small numbers the difference is negligible, and I think Math.abs is a much cleaner way of "self documenting" the code.

Kevin
Seriously... http://tinyurl.com/yjwb498
Christopher W. Allen-Poole
Use negation instead. No function call needed. http://stackoverflow.com/questions/1701822/making-a-variable-value-positive/1702175#1702175
Kelly French
I have to agree with @Kevin here. while "a = -a;" is explicit, it still triggers math phobia in some people which includes developers. Math.abs() seems to say the same thing but uses a different part of the brain. I wouldn't comment Math.abs() but i might for "a = -a".
Kelly French
+1  A: 

This isn't a jQuery implementation but uses the Math library from Javascript

x = Math.abs(x);

NickGPS
A: 

or, if you want to avoid function call (and branching), you can use this code:

x = (x ^ (x >> 31)) - (x >> 31);

it's a bit "hackish" and it looks nice in some odd way :) but I would still stick with Math.abs (just wanted to show one more way of doing this)

btw, this works only if underlying javascript engine stores integers as 32bit, which is case in firefox 3.5 on my machine (which is 32bit, so it might not work on 64bit machine, haven't tested...)

krcko
Sure, it is another way. But it is not clear what you do, less readable than Math.abs and if that isn't enough, it is also slower than Math.abs(x) on Firefox 3.6. If you must complicate things, use `x < 0 ? -x : x` (the fastest in the other tested browsers). Your code is 1% slower in Opera 10.63, 12% slower in Chrome 6.0 and 20% slower in IE8.
some
+5  A: 

Between these two choices (thanks to @Kooilnc for the example):

Number.prototype.abs = function(){
    return Math.abs(this);
};

and

var negative = -23, 
    positive = -negative>0 ? : -negative : negative;

go with the second (negation). It doesn't require a function call and the CPU can do it in very few instructions. Fast, easy, and efficient.

Kelly French