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

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

提交回复
热议问题