ian
ian

Reputation: 12335

making a variable value positive

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?

Upvotes: 52

Views: 72872

Answers (6)

kemiller2002
kemiller2002

Reputation: 115498

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.

Upvotes: 61

Ash Pettit
Ash Pettit

Reputation: 457

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

Upvotes: 1

Kelly S. French
Kelly S. French

Reputation: 12334

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.

Upvotes: 28

krcko
krcko

Reputation: 2834

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...)

Upvotes: 2

NickGPS
NickGPS

Reputation: 1519

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

x = Math.abs(x);

Upvotes: 3

kgiannakakis
kgiannakakis

Reputation: 104178

if (myvar < 0) {
  myvar = -myvar;
}

or

myvar = Math.abs(myvar);

Upvotes: 17

Related Questions