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.
JavaScript
x
4
1
x = -25
2
x = x * x
3
x = Math.sqrt(x)
4
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.
JavaScript
1
3
1
var x = -25;
2
x = Math.abs(x); // x would now be 25
3
console.log(x);
Here are some test cases from the documentation:
JavaScript
1
6
1
Math.abs('-1'); // 1
2
Math.abs(-2); // 2
3
Math.abs(null); // 0
4
Math.abs("string"); // NaN
5
Math.abs(); // NaN
6