Get the absolute value of a number in Javascript

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

Solution 5 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDan WalmsleyView Question on Stackoverflow
Solution 1 - JavascriptDarin DimitrovView Answer on Stackoverflow
Solution 2 - JavascriptEndre SimoView Answer on Stackoverflow
Solution 3 - JavascriptRickView Answer on Stackoverflow
Solution 4 - JavascriptchisophugisView Answer on Stackoverflow
Solution 5 - JavascriptKamil KiełczewskiView Answer on Stackoverflow