在Javascript中获取数字的绝对值 [英] Get the absolute value of a number in Javascript
问题描述
我想在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 = sqrt(x)
// x would now be 25
JavaScript中有没有办法简单地删除标志一个比数学方法更有效的数字?
Is there a way in JavaScript to simply drop the sign of a number that is more efficient than the mathematical approach?
推荐答案
你的意思是得到一个数字的绝对值? Math.abs
javascript函数专为此目的而设计。
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
以下是文档中的一些测试用例:
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
这篇关于在Javascript中获取数字的绝对值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!