How to calculate modulo of negative integers in JavaScript?

10,498

Solution 1

You can try this :p-

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

Check out this

Solution 2

Most languages which inherit from C will return a negative result if the first operand of a modulo operation is negative and the second is positive. I'm not sure why this decision was made originally. Probably closest to what processors at that time did in assembly. In any case, since then the answer to “why” is most likely “because that's what programmers who know C expect”.

The MDC Reference contains a pointer to a proposal to introduce a proper mod operator. But even that would keep the existing % operator (which they call “remainder” to better distinguish between them) and introduce a new infix word notation a mod b. The proposal dates from 2011, and I know no more recent developments in this direction.

Share:
10,498

Related videos on Youtube

jeff
Author by

jeff

Updated on September 29, 2022

Comments

  • jeff
    jeff over 1 year

    I'm trying to iterate over an array of jQuery objects, by incrementing or decrementing by 1. So, for the decrementing part, I use this code:

    var splitted_id = currentDiv.attr('id').split('_');
    var indexOfDivToGo = parseInt(splitted_id[1]);
    indexOfDivToGo = (indexOfDivToGo-1) % allDivs.length;
    var divToGo = allDivs[indexOfDivToGo];
    

    so I have 4 elements with id's:

    div_0
    div_1
    div_2
    div_3
    

    I was expecting it to iterate as 3 - 2 - 1 - 0 - 3 - 2 - etc..

    but it returns -1 after the zero, therefore it's stuck. So it iterates as:

    3 - 2 - 1 - 0 - -1 - stuck

    I know I can probably fix it by changing the second line of my code to

    indexOfDivToGo = (indexOfDivToGo-1 + allDivs.length) % allDivs.length;
    

    but I wonder why JavaScript is not calculating negative mods. Maybe this will help another coder fellow too.

  • jeff
    jeff over 10 years
    I remember that C did not have this problem, but it was a long time ago. And I didn't know JavaScript is a descendant of C :) Thanks for your answer.
  • MvG
    MvG over 10 years
    See e.g. this poster for details on the evolution of programming languages. The Wikipedia page lists: “Influenced by Self, HyperTalk, AWK, C, Perl, Python, Java, Scheme”.
  • Marcel
    Marcel over 6 years
    Can you explain why you modulo twice? I would think (this + n) % n would be enough.
  • jjmontes
    jjmontes about 3 years
    @Marcel if modulo is 360 and the input is -710, your approach wouldn't work.