Skip to content
Advertisement

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

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

According to Javascript (see this JSBin) it is -13.

How do I fix this?

Advertisement

Answer

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

Taken from this article: The JavaScript Modulo Bug

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement