According to Google Calculator (-13) % 64
is 51
.
According to Javascript (see this JSBin) it is -13
.
How do I fix this?
When remainder or %(modulo) is calculated on positive numbers then both behave similar but when negative numbers are used then both behave differently. The JavaScript %(modulo) behaves like remainder operation and gives the remainder and as the number is negative therefore remainder also comes out to be negative.
Can a modulus be negative? % can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.
The answer is “Yes”. Reason: The value of modulus of any number is always positive. where x = positive value, negative value or zero.
Therefore, in C/C++ language we always find remainder as (a%b + b)%b (add quotient to remainder and again take remainder) to avoid negative remainder.
Number.prototype.mod = function (n) { return ((this % n) + n) % n; };
Taken from this article: The JavaScript Modulo Bug
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: http://jsperf.com/negative-modulo/2
~97% faster than using prototype. If performance is of importance to you of course..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With