JavaScript % (Modulo) Gives a Negative Result for Negative Numbers

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

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

Taken from this article: The JavaScript Modulo Bug

How to calculate modulo of negative integers in JavaScript?

You can try this :p-

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

Check out this

Mod with negative numbers gives a negative result in Java and C

The % operator is treated as a remainder operator, so the sign of the result is the same as that of the dividend.

If you want a modulo function, you can do something like this:

int mod(int a, int b)
{
int ret = a % b;
if (ret < 0)
ret += b;
return ret;
}

How does JavaScript handle modulo?

Exactly as every language handles modulo: The remainder of X / Y.

47 % 8 == 7

Also if you use a browser like Firefox + Firebug, Safari, Chrome, or even IE8+ you could test such an operation as quickly as hitting F12.

Modulus operator not behaving as expected in javascript?

mod is the leftover when you divide the number by the divider.

In Math -1%5 = -1 so Js is working as expected.

You are not doing anything wrong. If you want to get a positive number (the difference) add the divider number to the result.

var result = (-1 % 5) + 5;

It doesn't matter where you add the number before the module or after. Its a pure math.

Modulo and Negative Number in Math?

In mathematics, the modulus must be >1 and the convention is that the modulo operation yields the smallest non-negative integer solution to a+km=b:

-7 mod  2 = 1
7 mod -2 Illegal
-7 mod -2 Illegal

It is easy to extend the definition to include negative numbers (and 1 and -1):

-7 mod  2 = 1
7 mod -2 = 1
-7 mod -2 = 1
-7 mod 3 = 2

But in computing, different languages use different conventions:

-7 mod  2 = {1, or -1, or undefined}

I suspect that your system says -7 mod 2 = -1, so that isEvenOrOdd(-7); yields 'even' (because -1 ≠ 1).

Make a function similar to modulo that also works with negative numbers

Modulo operation behavior depends on programming language - see table here

For example, in Python print(-4 % 3) gives 2

Seems you are using C-like language, where remainder has the same sign as dividend. In this case you can use such formula (ideone)

(a % b + b) % b 

Also the only comparison is enough to correct negative value (so avoiding double %)

rem = a % b;
if (rem < 0) rem += b;


Related Topics



Leave a reply



Submit