Javascript Math Object Methods - negatives to zero

跟風遠走 提交于 2019-11-29 01:20:18

问题


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

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

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


回答1:


Just do something like

value = value < 0 ? 0 : value;

or

if (value < 0) value = 0;

or

value = Math.max(0, value);



回答2:


I suppose you could use Math.max().

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

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



回答3:


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.




回答4:


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

// or 

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



回答5:


x < 0 ? 0 : x does the job .




回答6:


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.




回答7:


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/



来源:https://stackoverflow.com/questions/4924842/javascript-math-object-methods-negatives-to-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!