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?
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.
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).
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.
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.
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
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With