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?
Advertisement
Answer
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