68

I want to get the absolute value of a number in JavaScript. That is, drop the sign. I know mathematically I can do this by squaring the number then taking the square root, but I also know that this is horribly inefficient.

x = -25
x = x * x 
x = Math.sqrt(x)
console.log(x)

Is there a way in JavaScript to simply drop the sign of a number that is more efficient than the mathematical approach?

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Dan Walmsley
  • 2,765
  • 7
  • 26
  • 45

6 Answers6

123

You mean like getting the absolute value of a number? The Math.abs javascript function is designed exactly for this purpose.

var x = -25;
x = Math.abs(x); // x would now be 25 
console.log(x);

Here are some test cases from the documentation:

Math.abs('-1');     // 1
Math.abs(-2);       // 2
Math.abs(null);     // 0
Math.abs("string"); // NaN
Math.abs();         // NaN
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
16

Here is a fast way to obtain the absolute value of a number. It's applicable on every language:

x = -25;
console.log((x ^ (x >> 31)) - (x >> 31));
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Endre Simo
  • 11,330
  • 2
  • 40
  • 49
9

If you want to see how JavaScript implements this feature under the hood you can check out this post.

Blog Post

Here is the implementation based on the chromium source code.

function MathAbs(x) {
  x = +x;
  return (x > 0) ? x : 0 - x;
}

console.log(MathAbs(-25));
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Rick
  • 12,606
  • 2
  • 43
  • 41
  • 2
    @AndreFigueiredo - I think it answers it quite well, although definitely a bit terse. It's suggesting you could use `absx=Math.abs(x);` or you could create a function (`MathAbs`) or even directly use `absx=(x > 0) ? x : 0 - x;`. Perhaps adding a similar statement to the answer would help. – Kevin Fegan Oct 08 '16 at 17:46
7

I think you are looking for Math.abs(x)

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/abs

chisophugis
  • 789
  • 5
  • 8
3

Alternative solution

Math.max(x,-x)

let abs = x => Math.max(x,-x);

console.log( abs(24), abs(-24) );

Also the Rick answer can be shorted to x>0 ? x : -x

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

to simply drop the sign of a number

var x = -25;
+`${x}`.replace('-', '');
oleedd
  • 388
  • 2
  • 15