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

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

$
0
0

Using Number.prototype is SLOW, because each time you use the prototype method your number is wrapped in an Object. Instead of this:

Number.prototype.mod = function(n) {  return ((this % n) + n) % n;}

Use:

function mod(n, m) {  return ((n % m) + m) % m;}

See: https://jsperf.app/negative-modulo/2

~97% faster than using prototype. If performance is of importance to you of course..


Viewing all articles
Browse latest Browse all 14

Trending Articles



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