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

Alec Gorge picture Alec Gorge · Dec 17, 2010 · Viewed 82.7k times · Source

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

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

How do I fix this?

Answer

Enrique picture Enrique · Dec 17, 2010
Number.prototype.mod = function(n) {
    return ((this%n)+n)%n;
};

Taken from this article: The JavaScript Modulo Bug