Javascript Math Object Methods - negatives to zero
59,366
Solution 1
Just do something like
value = value < 0 ? 0 : value;
or
if (value < 0) value = 0;
or
value = Math.max(0, value);
Solution 2
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
Solution 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.
Solution 4
Math.positive = function(num) {
return Math.max(0, num);
}
// or
Math.positive = function(num) {
return num < 0 ? 0 : num;
}
Solution 5
x < 0 ? 0 : x
does the job .
Related videos on Youtube
Author by
FFish
Updated on October 16, 2021Comments
-
FFish over 2 years
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 90Is there anything like that? I have just rounded numbers.
-
Skeep over 9 yearsQuick JSPerf shows value = value < 0 ? 0 : value; is on top jsperf.com/negatives-to-zero
-
ksugiarto almost 9 yearsThis one should be the accepted answer in my opinion. Just saying... :)
-
Matt Fletcher over 6 yearsI like the
Math.max
one the most, because it only requires referencingvalue
once -
Killy over 6 yearszero is neither positive nor negative, your function should be renamed according to that
-
jwerre over 5 yearsOne thing to keep in mind is that both
Math.max(0, NaN)
andMath.max(0, undefined)
returnNaN
so you may want to do something along these lines:Math.max(0, num) || 0
-
insign about 3 yearsIn a more fair benchmark, Math.max wins probably because it was already instantiated once. jsbench.me/tbkmm8varf/1
-
squarecandy over 2 years@insign - I'm getting different results every time I run your benchmark - sometimes a 3 way tie. Seems like readability and consistency are more important factors if the margins are so close between them.
-
RedGuy11 about 2 yearsWhat's the
~~
? -
kungfooman almost 2 years@RedGuy11 The
~~
is obstrusive and wrong, it converts it to binary. Which in turn makes it work ONLY for integers:~~.1 == 0
Not sure why this is upvoted so often, no one sees how wrong it is?