JavaScript中是否有数学函数可以将数字转换为正数?


当前回答

乘以(-1)是将负数转换为正数的最快方法。但是你要小心,不要把我的错误的正数转换成负数!所以需要额外的检查…

那么数学。abs、数学。floor和parseInt是最慢的。

https://jsperf.com/test-parseint-and-math-floor-and-mathabs/1

其他回答

unsigned_value = Math.abs(signed_value);

那么x *= -1呢?我喜欢它的简洁。

我知道这有点晚了,但对于那些纠结于此的人,你可以使用以下函数:

将任何数字变为正数 令x = 54; 令y = -54; let resultx = Math.abs(x);/ / 54 let result = Math.abs(y);/ / 54 将任何数字变为负数 令x = 54; 令y = -54; let resultx = -Math.abs(x);/ / -54 let result = -Math.abs(y);/ / -54 求任意数的倒数 令x = 54; 令y = -54; 令resultx = -(x);/ / -54 令result = -(y);/ / 54

var posNum = (num < 0) ? num * -1 : num; // if num is negative multiple by negative one ... 

我觉得这个解决办法很容易理解。

你可以用这个…

Math.abs(x)

Math .abs() | MDN