Javascript 数学对象方法 - 负数为零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4924842/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:48:19  来源:igfitidea点击:

Javascript Math Object Methods - negatives to zero

javascriptmathnegative-number

提问by FFish

in Javascript I can't seem to find a method to set negatives to zero?

在 Javascript 中,我似乎找不到将负数设置为零的方法?

-90 becomes 0
-45 becomes 0
0 becomes 0
90 becomes 90

-90 变成 0
-45 变成 0
0 变成 0
90 变成 90

Is there anything like that? I have just rounded numbers.

有这样的吗?我刚刚四舍五入的数字。

回答by aioobe

Just do something like

只是做类似的事情

value = value < 0 ? 0 : value;

or

或者

if (value < 0) value = 0;

or

或者

value = Math.max(0, value);

回答by RightSaidFred

I suppose you could use Math.max().

我想你可以使用Math.max().

var num = 90;
num = Math.max(0,num); // 90

var num = -90;
num = Math.max(0,num); // 0

回答by SLaks

If you want to be clever:

如果你想变得聪明:

num = (num + Math.abs(num)) / 2;

However, Math.maxor a conditional operator would be much more understandable.
Also, this has precision issues for large numbers.

但是,Math.max或者条件运算符会更容易理解。
此外,这对于大量数字存在精度问题。

回答by Juan Mendes

Math.positive = function(num) {
  return Math.max(0, num);
}

// or 

Math.positive = function(num) {
  return num < 0 ? 0 : num;
}

回答by Alexandre C.

x < 0 ? 0 : xdoes the job .

x < 0 ? 0 : x做这份工作。

回答by Killy

Remember the negative zero.

记住负零。

function isNegativeFails(n) {
    return n < 0;
}
function isNegative(n) {
    return ((n = +n) || 1 / n) < 0;
}
isNegativeFails(-0); // false
isNegative(-0); // true
Math.max(-0, 0); // 0
Math.min(-0, 0); // -0

Source: http://cwestblog.com/2014/02/25/javascript-testing-for-negative-zero/

资料来源:http: //cwestblog.com/2014/02/25/javascript-testing-for-negative-zero/

回答by jacobangel

I don't believe that such a function exists with the native Math object. You should write a script to fill in the function if you need to use it.

我不相信这样的函数存在于本机 Math 对象中。如果您需要使用它,您应该编写一个脚本来填充该函数。