Elias Benevedes
Elias Benevedes

Reputation: 391

How does JavaScript handle modulo?

I was wondering how JavaScript handles modulo. For example, what would JavaScript evaluate 47 % 8 as? I can’t seem to find any documentation on it, and my skills on modulo aren’t the best.

Upvotes: 2

Views: 3812

Answers (4)

Grant mitchell
Grant mitchell

Reputation: 529

TO better understand modulo here is how its built;

function modulo(num1, num2) {
    if (typeof num1 != "number" || typeof num2 != "number"){
      return NaN
    }
    var num1isneg=false
     if (num1.toString().includes("-")){
      num1isneg=true
    }
      num1=parseFloat(num1.toString().replace("-",""))
      var leftover =parseFloat( ( parseFloat(num1/num2) - parseInt(num1/num2)) *num2)
      console.log(leftover)
            if (num1isneg){
              var z = leftover.toString().split("")
              z= ["-", ...z]
              leftover = parseFloat(z.join(""))
            }
            return leftover
}

Upvotes: 0

1j01
1j01

Reputation: 4199

Javascript's modulo operator returns a negative number when given a negative number as input (on the left side).

14 % 5 // 4
15 % 5 // 0
-15 % 5 // -0
-14 % 5 // -4

(Note: negative zero is a distinct value in JavaScript and other languages with IEEE floats, but -0 === 0 so you usually don't have to worry about it.)

If you want a number that is always between 0 and a positive number that you specify, you can define a function like so:

function mod(n, m) {
    return ((n % m) + m) % m;
}
mod(14, 5) // 4
mod(15, 5) // 4
mod(-15, 5) // 0
mod(-14, 5) // 1

comparison of remainder and modulo

Upvotes: 2

Owen Allen
Owen Allen

Reputation: 11968

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.

Upvotes: 3

nobrandheroes
nobrandheroes

Reputation: 758

Modulo should behave like you expect. I expect.

47 % 8 == 7

Fiddle Link

Upvotes: 0

Related Questions