javascriptmathmodulo

JavaScript % (modulo) gives a negative result for negative numbers


According to Google Calculator (-13) % 64 is 51.

According to JavaScript, it is -13.

console.log(-13 % 64);

How do I fix this?


Solution

  • Number.prototype.mod = function (n) {
      "use strict";
      return ((this % n) + n) % n;
    };
    

    Taken from this article: The JavaScript Modulo Bug