Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript calculate sum unless it is less than zero

Just a quick question, can this sum be written in one short line:

  a = (b / c) * 100;
  if (a < 0) a = 0;

Apart from the obvious way which is equally long:

 if ((b / c) * 100) > 0) a = (b / c) * 100; else a = 0;

EDIT: And the ternary version of this is no different, I didn't think I needed to mention.

Maybe there isn't a short, neat and clever way to write this but I was just hoping there was since it always seems unnecessary to have that extra line underneath.

like image 371
Hasen Avatar asked Jan 26 '23 00:01

Hasen


1 Answers

You could take Math.max along with zero.

a = Math.max(b * 100 / c, 0);
like image 136
Nina Scholz Avatar answered Feb 12 '23 12:02

Nina Scholz