数学对象方法-负数为零

在 Javascript 中,我似乎找不到一个方法来设置负值为零?

-90变成0
-45变成0
0变成0
90变成90 < br/>

有类似的东西吗? 我只有四舍五入的数字。

64657 次浏览

Just do something like

value = value < 0 ? 0 : value;

or

if (value < 0) value = 0;

or

value = Math.max(0, value);

I suppose you could use Math.max().

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


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

x < 0 ? 0 : x does the job .

If you want to be clever:

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

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

function makeNegativeNumberZero(num) {
return !!Math.max(0, num);
}


// or


function makeNegativeNumberZero(num) {
return num < 0 ? 0 : num;
}

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/

Well value = Math.max(0,value) is just neat but after 10 years, i just don't want one other nice method to go unmentioned.

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


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

This method can be used