-1

how would i stop the below returning a value less than 0. I want anything less than 0 to show as 0. Any help appreciated.

$("#spanrPower_CO2").text (Math.round(-data[0] * 16.8) * 100 / 100);
BjH
  • 33
  • 2
  • 4
    `Math.max(0, Math.round(-data[0] * 16.8) * 100 / 100);` – 001 Sep 22 '16 at 13:56
  • 1
    You will probably get your intended result with clearer code as `Math.max(0, -data[0] * 16.8).toFixed(2)`. See http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-in-javascript – Lutz Lehmann Sep 22 '16 at 14:07
  • @LutzL: nicer than my answer methinks. Do consider promoting it. – Bathsheba Sep 22 '16 at 14:09
  • Use an extra line of code or two, and make it crystal clear: `if ( value < 0 ) { value = 0; }`. – Teepeemm Sep 22 '16 at 14:21
  • this worked great thanks! (Math.max(0, -data[0] * 16.8).toFixed(0)); – BjH Sep 22 '16 at 15:07

2 Answers2

2

data[0] > 0 ? 0 : -Math.round(16.8 * data[0]); is probably clearer.

Note that unless you're approaching floating point infinity, * 100 / 100 is a no-op.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0
(Math.max(0, -data[0] * 16.8).toFixed(0));
BjH
  • 33
  • 2