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 square, but I also know that it is terribly inefficient.

x = -25 x = x * xx = sqrt(x) // x would now be 25 

Is there a way in JavaScript to simply abandon the sign of a number, which is more efficient than a mathematical approach?

+53
javascript
Feb 19 '12 at 22:32
source share
5 answers

Do you mean to get the absolute value of a number? Math.abs javascript function is just for that purpose.

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

Here are some examples from the documentation:

 Math.abs('-1'); // 1 Math.abs(-2); // 2 Math.abs(null); // 0 Math.abs("string"); // NaN Math.abs(); // NaN 
+102
Feb 19 '12 at 22:33
source share

Here is a quick way to get the absolute value of a number. This applies in every language:

 (x ^ (x >> 31)) - (x >> 31); 
+12
Aug 08 2018-12-12T00:
source share
+7
Feb 19 '12 at 22:34
source share

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

Blog post

Here is an implementation based on the chromium source code.

 function MathAbs(x) { x = +x; return (x > 0) ? x : 0 - x; } 
+7
May 30 '16 at 19:53
source share

Good for writing only, there might be another simplified method:

 var abs = x => Math.sqrt(x*x) 
0
Dec 08 '17 at 11:14
source share



All Articles