3
-224 / -37.333333333333336 = 6
-224 % -37.333333333333336 = -37.33333333333332
(-224 / -37.333333333333336) % 1 = 0

Why doesn't % return 0 if the first result is 6?

And why isn't the result a float in the third calculation?

phant0m
  • 16,595
  • 5
  • 50
  • 82
Somebody
  • 9,316
  • 26
  • 94
  • 142
  • 1
    Well the last one makes sense; dividing by 1 leaves a remainder of zero in all cases. It's the second one that's hurting my head. – Pointy Aug 21 '13 at 17:47
  • 1
    @Pointy It's a rounding issue, if you remove some threes at the end, you get a value close to zero. – phant0m Aug 21 '13 at 17:49
  • 1
    @phant0m this is not just a simple question about how floating-point math works. Can you explain the second operation in the OP? – Pointy Aug 21 '13 at 17:49
  • @Pointy, `-224 / -37.333333333333337` is also `6`, and `-224 / -37.333333333333338` too. It's looks like a precision issue, I believe phant0m is right. – bfavaretto Aug 21 '13 at 17:51
  • @Somebody the result in the third calculation **is** a float; **all** numbers are floats in JavaScript. The fact that it's not *printed* as a float is just an artifact of the way numbers are turned into strings. – Pointy Aug 21 '13 at 17:51
  • @bfavaretto yes but that result just seems wildly off. (*edit* ok I think I'm starting to get it) – Pointy Aug 21 '13 at 17:54

1 Answers1

4

All numbers in JavaScript are 64-bit floating point numbers. Just because it doesn't display the number as 0.0 doesn't mean it's not a double.

According to WolframAlpha:

-224 / -37.333333333333336 = 5.9999999999999995714285...

Due to accuracy limitations / rounding in floating point division, the division results in 6 in JavaScript.

The modulo operation, however, correctly sees that -37.3… doesn't quite fit into -224 six times. That means that the other 99.99…% of -37.33… is a leftover after the division, which corresponds to result of the modulo operation.

Hence, you get almost, but not quite, the divisor back.

phant0m
  • 16,595
  • 5
  • 50
  • 82