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

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

提交回复
热议问题