在 JavaScript 中将负数转换为正数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4652104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a negative number to a positive one in JavaScript
提问by dave
Is there a math function in JavaScript that converts numbers to positive value?
JavaScript 中是否有将数字转换为正值的数学函数?
回答by ChrisNel52
回答by gnclmorais
What about x *= -1
? I like its simplicity.
怎么样x *= -1
?我喜欢它的简单。
回答by orlp
Math.abs(x)
or if you are certainthe value is negative before the conversion just prepend a regular minus sign: x = -x
.
Math.abs(x)
或者,如果您在转换之前确定该值是负数,则只需在前面加上一个常规的减号:x = -x
。
回答by Highway of Life
The minus sign (-) can convert positive numbers to negative numbers and negative numbers to positive numbers. x=-y
is visual sugar for x=(y*-1)
.
减号 (-) 可以将正数转换为负数,将负数转换为正数。x=-y
是视觉糖x=(y*-1)
。
var y = -100;
var x =- y;
回答by Marc B
unsigned_value = Math.abs(signed_value);
回答by MarkD
var posNum = (num < 0) ? num * -1 : num; // if num is negative multiple by negative one ...
I find this solution easy to understand.
我发现这个解决方案很容易理解。
回答by Kyle
If you'd like to write interesting code that nobody else can ever update, try this:
如果您想编写其他人无法更新的有趣代码,请尝试以下操作:
~--x
~--x
回答by Adeel Imran
I know this is a bit late, but for people struggling with this, you can use the following functions:
我知道这有点晚了,但是对于为此苦苦挣扎的人,您可以使用以下功能:
Turn any number positive
let x = 54; let y = -54; let resultx = Math.abs(x); // 54 let resulty = Math.abs(y); // 54
Turn any number negative
let x = 54; let y = -54; let resultx = -Math.abs(x); // -54 let resulty = -Math.abs(y); // -54
Invert any number
let x = 54; let y = -54; let resultx = -(x); // -54 let resulty = -(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 = -Math.abs(x); // -54 let resulty = -Math.abs(y); // -54
反转任何数字
let x = 54; let y = -54; let resultx = -(x); // -54 let resulty = -(y); // 54
回答by Bashirpour
Negative to positive
负对正
var X = -10 ;
var number = Math.abs(X); //result 10
Positive to negative
正转负
var X = 10 ;
var number = (X)*(-1); //result -10
回答by Combine
Multiplying by (-1) is the fastest way to convert negative number to positive. But you have to be careful not to convert my mistake a positive number to negative! So additional check is needed...
乘以 (-1) 是将负数转换为正数的最快方法。但是你必须小心不要将我的错误从正数转换为负数!所以需要额外的检查...
Then Math.abs, Math.floor and parseInt is the slowest.
然后 Math.abs、Math.floor 和 parseInt 是最慢的。
https://jsperf.com/test-parseint-and-math-floor-and-mathabs/1
https://jsperf.com/test-parseint-and-math-floor-and-mathabs/1