Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

According to Google Calculator (-13) % 64 is 51.

According to Javascript (see this JSBin) it is -13.

How do I fix this?

like image 422
Alec Gorge Avatar asked Dec 17 '10 03:12

Alec Gorge


People also ask

How does JavaScript handle negative modulo?

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 the result of modulo 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.

Is Result of modulo always positive?

The answer is “Yes”. Reason: The value of modulus of any number is always positive. where x = positive value, negative value or zero.

How do you avoid negative modulo?

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.


2 Answers

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

Taken from this article: The JavaScript Modulo Bug

like image 90
Enrique Avatar answered Oct 17 '22 01:10

Enrique


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..

like image 41
StuR Avatar answered Oct 17 '22 00:10

StuR