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

前端 未结 11 1467
死守一世寂寞
死守一世寂寞 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 12:07

    This is not a bug, there's 3 functions to calculate modulo, you can use the one which fit your needs (I would recommend to use Euclidean function)

    Truncating the decimal part function

    console.log(  41 %  7 ); //  6
    console.log( -41 %  7 ); // -6
    console.log( -41 % -7 ); // -6
    console.log(  41 % -7 ); //  6
    

    Integer part function

    Number.prototype.mod = function(n) {
        return ((this%n)+n)%n;
    };
    
    console.log( parseInt( 41).mod( 7) ); //  6
    console.log( parseInt(-41).mod( 7) ); //  1
    console.log( parseInt(-41).mod(-7) ); // -6
    console.log( parseInt( 41).mod(-7) ); // -1
    

    Euclidean function

    Number.prototype.mod = function(n) {
        var m = ((this%n)+n)%n;
        return m < 0 ? m + Math.abs(n) : m;
    };
    
    console.log( parseInt( 41).mod( 7) ); // 6
    console.log( parseInt(-41).mod( 7) ); // 1
    console.log( parseInt(-41).mod(-7) ); // 1
    console.log( parseInt( 41).mod(-7) ); // 6
    

提交回复
热议问题