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 .

Share:
59,366

Related videos on Youtube

FFish
Author by

FFish

Updated on October 16, 2021

Comments

  • FFish
    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 90

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

  • Skeep
    Skeep over 9 years
    Quick JSPerf shows value = value < 0 ? 0 : value; is on top jsperf.com/negatives-to-zero
  • ksugiarto
    ksugiarto almost 9 years
    This one should be the accepted answer in my opinion. Just saying... :)
  • Matt Fletcher
    Matt Fletcher over 6 years
    I like the Math.max one the most, because it only requires referencing value once
  • Killy
    Killy over 6 years
    zero is neither positive nor negative, your function should be renamed according to that
  • jwerre
    jwerre over 5 years
    One thing to keep in mind is that both Math.max(0, NaN) and Math.max(0, undefined) return NaN so you may want to do something along these lines: Math.max(0, num) || 0
  • insign
    insign about 3 years
    In a more fair benchmark, Math.max wins probably because it was already instantiated once. jsbench.me/tbkmm8varf/1
  • squarecandy
    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
    RedGuy11 about 2 years
    What's the ~~?
  • kungfooman
    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?