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

javascript, math, modulo

Solution

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

Taken from this article: The JavaScript Modulo Bug

Problem

According to Google Calculator `(-13) % 64` is `51`. According to JavaScript, it is `-13`. ``` console.log(-13 % 64); ``` How do I fix this?

Original source

Related problems