# 在JavaScript中将负数转换为正数

2020/10/03 03:21 · javascript ·  · 0评论

JavaScript中是否存在将数字转换为正值的数学函数？

``````Math.abs(x)
``````

`Math​.abs()`| MDN

`x *= -1`我喜欢它的简单性。

`Math.abs(x)`或者，如果您确定转换前的值是负数，只需在前面加上一个常规的减号：`x = -x`

``````var y = -100;
var x =- y;
``````
``````unsigned_value = Math.abs(signed_value);
``````
``````var posNum = (num < 0) ? num * -1 : num; // if num is negative multiple by negative one ...
``````

• 将任何数字转为正数

``````let x =  54;
let y = -54;
let resultx =  Math.abs(x); //  54
let resulty =  Math.abs(y); //  54
``````
• 将任何数字变为负数

``````let x =  54;
let y = -54;
let resultx = -Math.abs(x); // -54
let resulty = -Math.abs(y); // -54
``````
• 倒数

``````let x =  54;
let y = -54;
let resultx = -(x);         // -54
let resulty = -(y);         //  54
``````

〜--x

``````var X = -10 ;
var number = Math.abs(X);     //result 10
``````

``````var X = 10 ;
var number = (X)*(-1);       //result -10
``````

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

``````num<0?num*=-1:'';
``````

``````var out = num<0?num*=-1:num; //I think someone already mentioned this variant.
``````

``````if(num<0)num*=-1;
``````

``````~--num; //Drawback for this is that num original value will be reduced by 1
``````

``````~(num = num-1);
``````

``````~num+1; //Wont change the actual num value, merely returns the new value
``````

``````~num++; //Wont display the right value.
``````

``````var num = -24;
num -= num*2;
console.log(num)
// result = 24``````

``````var x = 3;
x = (~x + 1);
console.log(x)
// result = -3``````

``````var x = -24;
var result = x * -1;
``````

``````var x = 58;
var result = x * -1;
``````

``````// NEGATIVE TO POSITIVE: ******************************************
var x = -24;
var result = x * -1;
console.log(result);

// VICE VERSA: ****************************************************
var x = 58;
var result = x * -1;
console.log(result);

// FLOATING POINTS: ***********************************************
var x = 42.8;
var result = x * -1;
console.log(result);

// FLOATING POINTS VICE VERSA: ************************************
var x = -76.8;
var result = x * -1;
console.log(result);``````

https://ramdajs.com/docs/#negate

``````function toPositive(n){
if(n < 0){
n = n * -1;
}
return n;
}
var a = toPositive(2);  // 2
var b = toPositive(-2); // 2
``````

``````function makePositive(n){
return Number((n*-n).toString().replace('-',''));
}
var a = makePositive(2);  // 2
var b = makePositive(-2); // 2
``````