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

前端 未结 11 1367
死守一世寂寞
死守一世寂寞 2020-11-22 11:01

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

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

How do I fix this

相关标签:
11条回答
  • 2020-11-22 11:48

    There is a NPM package that will do the work for you. You can install it with the following command.

    npm install just-modulo --save

    Usage copied from the README

    import modulo from 'just-modulo';
    
    modulo(7, 5); // 2
    modulo(17, 23); // 17
    modulo(16.2, 3.8); // 17
    modulo(5.8, 3.4); //2.4
    modulo(4, 0); // 4
    modulo(-7, 5); // 3
    modulo(-2, 15); // 13
    modulo(-5.8, 3.4); // 1
    modulo(12, -1); // NaN
    modulo(-3, -8); // NaN
    modulo(12, 'apple'); // NaN
    modulo('bee', 9); // NaN
    modulo(null, undefined); // NaN
    

    GitHub repository can be found via the following link:

    https://github.com/angus-c/just/tree/master/packages/number-modulo

    0 讨论(0)
  • 2020-11-22 11:54

    Though it isn't behaving as you expected, it doesn't mean that JavaScript is not 'behaving'. It is a choice JavaScript made for its modulo calculation. Because, by definition either answer makes sense.

    See this from Wikipedia. You can see on the right how different languages chose the result's sign.

    0 讨论(0)
  • 2020-11-22 11:55

    If x is an integer and n is a power of 2, you can use x & (n - 1) instead of x % n.

    > -13 & (64 - 1)
    51 
    
    0 讨论(0)
  • 2020-11-22 11:56

    So it seems that if you're trying to mod around degrees (so that if you have -50 degrees - 200 degrees), you'd want to use something like:

    function modrad(m) {
        return ((((180+m) % 360) + 360) % 360)-180;
    }
    
    0 讨论(0)
  • 2020-11-22 11:56

    I deal with négative a and negative n too

     //best perf, hard to read
       function modul3(a,n){
            r = a/n | 0 ;
            if(a < 0){ 
                r += n < 0 ? 1 : -1
            }
            return a - n * r 
        }
        // shorter code
        function modul(a,n){
            return  a%n + (a < 0 && Math.abs(n)); 
        }
    
        //beetween perf and small code
        function modul(a,n){
            return a - n * Math[n > 0 ? 'floor' : 'ceil'](a/n); 
        }
    
    0 讨论(0)
  • 2020-11-22 11:58
    Number.prototype.mod = function(n) {
        return ((this%n)+n)%n;
    };
    

    Taken from this article: The JavaScript Modulo Bug

    0 讨论(0)
提交回复
热议问题