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?
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?
if (myvar < 0) {
myvar = -myvar;
}
or
myvar = Math.abs(myvar);
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.
This isn't a jQuery implementation but uses the Math library from Javascript
x = Math.abs(x);
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...)
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.