-1

I have the javascript equation:

var sbal=pfWeight-gWeight-adjm;
$("#result").html(sbal.toFixed(5));

If the result is 0, I assign the result the CSS color green. If it is not 0, I assign the result the CSS color red.

My problem is that sometimes the math comes out as -0 and thus displays as red.

I even tried

if(sbal===0){sbal=parseInt(0);}

sbal===0 returns true.

How can I work around this?

jsfiddle

I know that Are +0 and -0 the same? addresses WHY -0 = +0 but it does not supply and answer on how to fix the problem.

Community
  • 1
  • 1
Shawn
  • 3,031
  • 4
  • 26
  • 53

1 Answers1

1

If your only issue is that it sometimes returns -0, you can simply calculate the absolute value of your return value

Math.abs(-0); // 0

Edit: Javascript has a strange rounding of floating point numbers: If you roundup the result it works fine, then you don't need Math.abs(-0). As was pointed out -0 and 0 should be the same value.

This worked for me:

var sbal = Math.ceil(pfWeight - gWeight - adjm);
Pavlin
  • 5,390
  • 6
  • 38
  • 51