Dan Walmsley
Dan Walmsley

Reputation: 2821

How to get the absolute value of a number in JavaScript

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?

Upvotes: 67

Views: 56765

Answers (5)

Rick
Rick

Reputation: 13490

If you want to see how JavaScript implements this feature under the hood you can check out my blog post. As I wrote there, here is the implementation based on the chromium source code:

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

console.log(MathAbs(-25));

Upvotes: 9

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

The Math.abs javascript function is designed exactly for getting the absolute value.

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

Upvotes: 124

Endre Simo
Endre Simo

Reputation: 11551

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

x = -25;
console.log((x ^ (x >> 31)) - (x >> 31));

However, this will not work for integers whose absolute value is greater than 0x80000000 as the >> will convert x to 32-bits.

Upvotes: 15

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92347

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

Upvotes: 3

chisophugis
chisophugis

Reputation: 799

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

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

Upvotes: 7

Related Questions