Quantcast
Channel: JavaScript % (modulo) gives a negative result for negative numbers - Stack Overflow
Viewing all articles
Browse latest Browse all 14

Answer by wisbucky for JavaScript % (modulo) gives a negative result for negative numbers

$
0
0

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); // 1mod(63,64); // 63mod(64,64); // 0mod(65,64); // 1mod(0,64); // 0mod(-1,64); // 63mod(-13,64); // 51mod(-63,64); // 1mod(-64,64); // 0mod(-65,64); // 63

Viewing all articles
Browse latest Browse all 14

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>