Javascript Math Object Methods - negatives to zero

JavascriptMathNegative Number

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

Just do something like

value = value < 0 ? 0 : value;

or

if (value < 0) value = 0;

or

value = Math.max(0, value);

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

// or 

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

Solution 5 - Javascript

x < 0 ? 0 : x does the job .

Solution 6 - Javascript

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/

Solution 7 - Javascript

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFFishView Question on Stackoverflow
Solution 1 - JavascriptaioobeView Answer on Stackoverflow
Solution 2 - JavascriptRightSaidFredView Answer on Stackoverflow
Solution 3 - JavascriptSLaksView Answer on Stackoverflow
Solution 4 - JavascriptJuan MendesView Answer on Stackoverflow
Solution 5 - JavascriptAlexandre C.View Answer on Stackoverflow
Solution 6 - JavascriptKillyView Answer on Stackoverflow
Solution 7 - JavascriptReduView Answer on Stackoverflow