Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the absolute value of a number in Javascript

Tags:

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?

like image 334
Dan Walmsley Avatar asked Feb 19 '12 22:02

Dan Walmsley


People also ask

How do you type absolute values in typescript?

abs. Returns the absolute value of a number (the value without regard to whether it is positive or negative). For example, the absolute value of -5 is the same as the absolute value of 5.

What JS absolute value?

The abs() function returns the absolute value of a number. If the abs() function is passed a non-numeric value, an array with one than one element, or an empty object as the number parameter, the abs() function will return NaN (not a number).

How do you find the absolute value?

The absolute value (or modulus) | x | of a real number x is the non-negative value of x without regard to its sign. For example, the absolute value of 5 is 5, and the absolute value of −5 is also 5.

How do you take the absolute of a number in Java?

abs(int a) returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.


2 Answers

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 
like image 162
Darin Dimitrov Avatar answered Oct 05 '22 02:10

Darin Dimitrov


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));
like image 23
Endre Simo Avatar answered Oct 05 '22 00:10

Endre Simo