1

When Javascript's toFixed() method rounds to 0 from the negative side it gives -0 as the response. AFAIK -0 is not a real number and the response should be just 0.

Number(0.4).toFixed(0) => 0
Number(-0.4).toFixed(0) => -0

I can force the right answer by subtracting 0 from the response, which I need to do since drawing -0 on my chart looks really bad, but is -0 correct under any circumstances?

Here's a link to a jsFiddle showing the problem and my solution: http://jsfiddle.net/4sk870Lm/

Craig
  • 8,093
  • 8
  • 42
  • 74
  • 5
    possible duplicate of [Are +0 and -0 the same?](http://stackoverflow.com/questions/7223359/are-0-and-0-the-same) – nicael Oct 30 '14 at 22:27
  • Well, in math, `-0` is the case when you are approaching 0 from the negative side (for limits etc). It probably isn't useful in JS. – Evan Davis Oct 30 '14 at 22:27
  • What makes you think `-0` is not a real number? – Oriol Oct 30 '14 at 22:33
  • Since `-0` can be represented as an integer, it must be a [real number](http://en.wikipedia.org/wiki/Real_number). ;) – Felix Kling Oct 30 '14 at 22:34
  • @nicael I this instance I am interested in if rounding -0.4 should result in -0. I can see that there are some deep mathematics about negative infinity and what not. But -0.4 to the nearest integer (i.e. what toFixed is meant for) is just 0. – Craig Oct 30 '14 at 23:02
  • 1
    @Craig—the answer to "*if rounding -0.4 should result in -0*" is *Yes* since that's what the ECMAScript specification explicitly says should happen for both [*Math.round*](http://ecma-international.org/ecma-262/5.1/#sec-15.8.2.15) and [*Number.prototype.toFixed*](http://ecma-international.org/ecma-262/5.1/#sec-15.7.4.5). Note that there are browser bugs associated with this. – RobG Oct 30 '14 at 23:06
  • That looks really weird on a graph though. You don't know which way a number has been rounded when it displays just "1" why should it matter which side of 0 the number has rounded from? 0°C, 0mm of rain, etc. I don't like that specification. – Craig Oct 30 '14 at 23:33

1 Answers1

1

To solve this problem I simply subtracted 0 from the answer toFixed() have and that will convert -0 to 0

Number(-0.4).toFixed(0) -0

Craig
  • 8,093
  • 8
  • 42
  • 74