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

103,874

Solution 1

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

Taken from this article: The JavaScript Modulo Bug

Solution 2

Using Number.prototype is SLOW, because each time you use the prototype method your number is wrapped in an Object. Instead of this:

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

Use:

function mod(n, m) {
  return ((n % m) + m) % m;
}

See: http://jsperf.com/negative-modulo/2

~97% faster than using prototype. If performance is of importance to you of course..

Solution 3

The % operator in JavaScript is the remainder operator, not the modulo operator (the main difference being in how negative numbers are treated):

-1 % 8 // -1, not 7

Solution 4

A "mod" function to return a positive result.

var mod = function (n, m) {
    var remain = n % m;
    return Math.floor(remain >= 0 ? remain : remain + m);
};
mod(5,22)   // 5
mod(25,22)  // 3
mod(-1,22)  // 21
mod(-2,22)  // 20
mod(0,22)   // 0
mod(-1,22)  // 21
mod(-21,22) // 1

And of course

mod(-13,64) // 51

Solution 5

The accepted answer makes me a little nervous because it re-uses the % operator. What if Javascript changes the behavior in the future?

Here is a workaround that does not re-use %:

function mod(a, n) {
    return a - (n * Math.floor(a/n));
}

mod(1,64); // 1
mod(63,64); // 63
mod(64,64); // 0
mod(65,64); // 1
mod(0,64); // 0
mod(-1,64); // 63
mod(-13,64); // 51
mod(-63,64); // 1
mod(-64,64); // 0
mod(-65,64); // 63
Share:
103,874
Alec Gorge
Author by

Alec Gorge

Updated on February 18, 2022

Comments

  • Alec Gorge
    Alec Gorge about 2 years

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

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

    How do I fix this?