making a variable value positive
JavascriptMathJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
Use the Math.abs method.
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.
Solution 2 - Javascript
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.
Solution 3 - Javascript
if (myvar < 0) {
myvar = -myvar;
}
or
myvar = Math.abs(myvar);
Solution 4 - Javascript
This isn't a jQuery implementation but uses the Math library from Javascript
x = Math.abs(x);
Solution 5 - Javascript
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...)
Solution 6 - Javascript
If you don't feel like using Math.Abs you can you this simple if statement :P
if (x < 0) {
x = -x;
}
Of course you could make this a function like this
function makePositive(number) {
if (number < 0) {
number = -number;
}
}
makepositive(-3) => 3 makepositive (5) => 5
Hope this helps! Math.abs will likely work for you but if it doesn't this little