Quantcast
Viewing all articles
Browse latest Browse all 14

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

This is not a bug, there's 3 functions to calculate modulo, you can use the one which fit your needs (I would recommend to use Euclidean function)

Truncating the decimal part function

console.log(  41 %  7 ); //  6console.log( -41 %  7 ); // -6console.log( -41 % -7 ); // -6console.log(  41 % -7 ); //  6

Integer part function

Number.prototype.mod = function(n) {    return ((this%n)+n)%n;};console.log( parseInt( 41).mod( 7) ); //  6console.log( parseInt(-41).mod( 7) ); //  1console.log( parseInt(-41).mod(-7) ); // -6console.log( parseInt( 41).mod(-7) ); // -1

Euclidean function

Number.prototype.mod = function(n) {    var m = ((this%n)+n)%n;    return m < 0 ? m + Math.abs(n) : m;};console.log( parseInt( 41).mod( 7) ); // 6console.log( parseInt(-41).mod( 7) ); // 1console.log( parseInt(-41).mod(-7) ); // 1console.log( parseInt( 41).mod(-7) ); // 6

Viewing all articles
Browse latest Browse all 14

Trending Articles



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