1

I type this into google/wolfram alpha:

-15 % 360

and I get 345.

when I do it in javascript I get -15

https://www.google.com/search?q=-15%20%%20360

http://www.wolframalpha.com/input/?i=-15+mod+360

http://jsfiddle.net/BG3jW/

user2864740
  • 60,010
  • 15
  • 145
  • 220
y2k
  • 65,388
  • 27
  • 61
  • 86
  • Run it for yourself and see I have tested in every environment known to man from Dolphin, Safari, Chrome, Firefox, IE, Opera – y2k Apr 16 '14 at 23:12
  • Btw, Coffeescript fixes this with the `%%` operator. – elclanrs Apr 16 '14 at 23:19
  • It's not "broken". It is well defined in the [ECMAScript specification](http://es5.github.io/#x11.5.3). – user2864740 Apr 17 '14 at 00:08
  • modulo has to satisfy a%b=a-(a/b)*b relative to integer division. Now one had to decide what is more natural for the value of (-15)/360, 0 or -1. 0 gives a negative remainder, -1 the positive remainder. JS decides for rounding towards 0 in integer division, thus giving negative remainders. – Lutz Lehmann Apr 17 '14 at 07:04

1 Answers1

1

The % (remainder) operator is not "broken" in JavaScript, even though the result may be unexpected - especially with the anticipation of a stricter mathematical modulus operation.

The behavior is well-defined in ECMAScript. See 11.5.3 Applying the % Operator:

The % [remainder] operator yields the remainder of its operands from an implied division; the left operand is the dividend and the right operand is the divisor..

.. the [floating-point] remainder r from a dividend n and a divisor d is defined by the mathematical relation r = n − (d * q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive ..

In this manner it behaves in the same way as the remainder operator in Java or C# (for integer inputs).

There are arguments that it should be referred to as the remainder operator to avoid such confusion: ES5 does indeed implicitly refer to it as the "remainder operator", but the Mozilla JavaScript Reference calls it the "modulus operator".


See also Modulus operation with negatives values - weird thing?, which actually views the "brokeness" from the other angle.

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220