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

前端 未结 11 1472
死守一世寂寞
死守一世寂寞 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

    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
    

提交回复
热议问题