Great question!

It seems to me that ECMA is confusing and it's easy to miss how the modulo operator works (I certainly did). From ECMA-262 §11.5.3 there is a statement that:

The result of a floating-point remainder operation as computed by the % operator…

which infers a remainder operation. It goes on to provide an algorithm:

…where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from a dividend n and a divisor d is defined by the mathematical relation r = n − (d × q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d. r is computed and rounded to the nearest representable value using IEEE 754 round-to-nearest mode.

Applying that to the case of -1 % 4, then:

n = -1
d = 4
trueMathematicalQuotient = -1/4 = -0.25

Therefore q must be negative since n/d is negative. The largest negative integer that d (4) can be multiplied by that is less than or equal to -0.25 in magnitude and that the gives a result less than or equal to n (-1) is -0 (noting that -1 has greater magnitude than -0.25).

The simple way to do that is to truncate q to an integer:

q = -0 // -0.25 truncated

Putting numbers into the equation:

r = -1 - (4 * 0)
r = -1 - 0
r = -1

Which can be put in a function as:

function remainderMod(n, d) {
  var q = parseInt(n / d);  // truncates to lower magnitude
  return n - (d * q);
}

or abbreviated to:

function remainderMod(n, d) {
  return n - (d * (n/d | 0));
}
Answer from RobG on Stack Overflow
Top answer
1 of 4
4

Great question!

It seems to me that ECMA is confusing and it's easy to miss how the modulo operator works (I certainly did). From ECMA-262 §11.5.3 there is a statement that:

The result of a floating-point remainder operation as computed by the % operator…

which infers a remainder operation. It goes on to provide an algorithm:

…where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from a dividend n and a divisor d is defined by the mathematical relation r = n − (d × q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d. r is computed and rounded to the nearest representable value using IEEE 754 round-to-nearest mode.

Applying that to the case of -1 % 4, then:

n = -1
d = 4
trueMathematicalQuotient = -1/4 = -0.25

Therefore q must be negative since n/d is negative. The largest negative integer that d (4) can be multiplied by that is less than or equal to -0.25 in magnitude and that the gives a result less than or equal to n (-1) is -0 (noting that -1 has greater magnitude than -0.25).

The simple way to do that is to truncate q to an integer:

q = -0 // -0.25 truncated

Putting numbers into the equation:

r = -1 - (4 * 0)
r = -1 - 0
r = -1

Which can be put in a function as:

function remainderMod(n, d) {
  var q = parseInt(n / d);  // truncates to lower magnitude
  return n - (d * q);
}

or abbreviated to:

function remainderMod(n, d) {
  return n - (d * (n/d | 0));
}
2 of 4
2

The OP wanted to understand what is going on (not necessarily "fix" it). The short answer is that JavaScript has a "remainder" operator not a "modulo" operator (according to Douglas Crawford). For the full difference, here is a description of modulo vs remainder (specifically referring to C#).

Edit: Finally, the spec has the definitive answer.

🌐
W3Schools
w3schools.com › js › js_arithmetic.asp
JavaScript Arithmetic
In mathematics, the result of a modulo operation is the remainder of an arithmetic division.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Remainder
Remainder (%) - JavaScript | MDN
For two values of the same sign, ... which can make them differ by one unit of d. To obtain a modulo in JavaScript, in place of n % d, use ((n % d) + d) % d....
🌐
Codingem
codingem.com › home › javascript % operator: an ultimate guide to modulos
JavaScript % Operator: An Ultimate Guide to Modulos - codingem.com
July 10, 2025 - In JavaScript, you can use the % operator to calculate the remainder in division. The % operator is called the modulo operator.
🌐
freeCodeCamp
freecodecamp.org › news › javascript-modulo-operator-how-to-use-the-modulus-in-js
JavaScript Modulo Operator – How to Use the Modulus in JS
November 7, 2024 - This article will explain what the modulo operator in is JavaScript, how to use it, and what mathematical calculations it can perform.
🌐
Codeguppy
codeguppy.com › blog › javascript-modulo › index.html
JavaScript Modulo and the Caesar Cipher
At first sight the signed remainder ... to the modulo operator. Let’s do some tests by comparing the results returned by JavaScript with the ones returned by Google. In Chrome, open the console (press F12 and select the Console tab). Type there, one by one, the calculations from the left ...
🌐
Codecademy
codecademy.com › forum_questions › 54869a35d3292f85b3000519
Calculating Modulo in JavaScript | Codecademy
23 means 23/10 which is 2.3. Now you floor (round downwards) this to 2. Meaning you can put 2 full 10 in 23. but as 2*10 is not 23 but 20 you have a remainder of 23-20 = 3 And modulo gives you that remainder so e.g. for 17 its 3 full and 17-15 = 2 remaining aso ... In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language. Beginner Friendly.Beginner Friendly4 Lessons4 Lessons ... Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
🌐
Career Karma
careerkarma.com › blog › javascript › javascript modulo: a how-to guide
JavaScript Modulo: A How-To Guide | Career Karma
December 1, 2023 - The syntax for the modulo operator is: (number_one % number_two). Have you ever seen a percentage sign accompanied by a few numbers in JavaScript? You’ve maybe thought that it is something to do with calculating percentages. That’s not the case.
Find elsewhere
🌐
PlanetCalc
planetcalc.com › 8334
Online calculator: Mod calculator
This online calculator performs modulo operations on two given numbers, dividend and divisor. But those numbers should not be positive integers only; they can be, in fact, negative decimals as well (technically, the calculator accepts valid doubles - double-precision 64-bit floating-point numbers). The calculator returns the remainder of the division, called the modulus, according to an implementation in Javascript language.
Top answer
1 of 2
1

All of your code is correct and should work just fine. You need to actually display the result of this using a piece of JavaScript on the page load (for example).

In short, at the moment you have the result of your JavaScript function myModulo(5, 3) stored in the variable x. Now you haven't actually told the browser where to display this returned integer value - or even when to call the function in the DOM.

You might want to try...

window.onload = function() {
    var output = document.getElementById("output");
    output.innerHTML(myModulo(5, 3));
};

and having a div or p element (for example) which have the output id - i.e. <div id="output"></div>

2 of 2
0

Your code is just fine. You just need to update the view with the calculation result..

Here is an example of a working Mod calculator.

<!DOCTYPE html>
<html>
<head>
    <title>Modulo Calculator</title>
</head>
<body>
    <h1>Modulo Caculator </h1>
    <label for="dividend">Dividend</label>
    <input id="dividend">
    <label for="divisor">Divisor</label>
    <input id="divisor">
    <button id="calcBtn">Calculate</button>
    <p>Result is: <span id="result"></span></p>

    <script>
        // Your modulo function
        function myModulo(a,b) {
            return a % b;
        };

        // 
        var calcBtn = document.getElementById("calcBtn");
        var resultElement = document.getElementById("result");

        // Set onclick event to run the Mod and update the results
        calcBtn.onclick = function(){
            // Get values
            var dividend = document.getElementById("dividend").value;
            var divisor = document.getElementById("divisor").value;

            // Run Modulo function
            var modResult = myModulo(dividend, divisor);

            // Update Result
            resultElement.innerText = modResult;

        }

    </script>
</body>
</html>

Explanation of this code

  1. First of all we create 2 inputs that will store the dividend and the divisor (your 'a' and 'b'), a button to trigger the calculation action and a span element to display the result.
  2. Add an onclick event listener that will run each time the calculation button is clicked. This will execute a function that we define.
  3. Once the calculation button is clicked, our onclick function retrieves both arguments, the dividend and the divisor, and runs your myModulo function.
  4. After the result is returned, our onclick function displays it.

Hope this helps you understand more about JS and HTML interaction. Good luck

🌐
Josh W. Comeau
joshwcomeau.com › javascript › modulo-operator
Understanding the JavaScript Modulo Operator • Josh W. Comeau
COLORS.length is equal to 3, since there are 3 colors in our array. And so, as timeElapsed increments from 0 to 8, this function winds up performing the following sequence of calculations:
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-remainder-operator
JavaScript Remainder(%) Operator - GeeksforGeeks
July 23, 2025 - In JavaScript remainder takes the sign of the dividend and to get modulo ((a % n) + n) % n should be used instead of a % n. ... Example 1: This example returns the positive remainder in this case both modulo and remainder will be the same as ...
🌐
LogRocket
blog.logrocket.com › home › mastering the modulo operator in javascript: a complete guide
Mastering the modulo operator in JavaScript: A complete guide - LogRocket Blog
June 4, 2024 - In this example, the Spinner component uses the modulo operator to synchronize its animations. The mountDelay variable calculates the time remaining until the next second, which sets the animation-delay value.
🌐
Learn Math Class
learnmathclass.com › home › calculators › modulo calculator
Modulo Calculator | Interactive Modular Arithmetic Tool
January 15, 2024 - For float modulo, the calculator uses ... a - b \times \lfloor a/b \rfloora−b×⌊a/b⌋ to compute remainders with fractional values. This is useful for wrapping coordinates in graphics or handling periodic functions with non-integer periods. The calculator processes large numbers up to ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › modulus-arithmetic-operator-in-javascript
Modulus(%) Arithmetic Operator in JavaScript - GeeksforGeeks
July 23, 2025 - The modulus (%) arithmetic operator in JavaScript returns the remainder after dividing one number by another.
Top answer
1 of 6
20

For an IBAN calculation form a normal bankaccount number I end up with a very large number contained in a string datatype. From this large number I have to find the rest when divided by 97 -> large number % 97.

As soon as I convert the datatype to an integer I get an overflow resulting in a negative integer and eventually a wrong rest value. As I saw some verbose pieces of code (which also gave wrong outcome), I could not resist to share my own. Credits go to Finding Modulus of a Very Large Number with a Normal Number

modulo: function(divident, divisor) {
    var partLength = 10;

    while (divident.length > partLength) {
        var part = divident.substring(0, partLength);
        divident = (part % divisor) +  divident.substring(partLength);          
    }

    return divident % divisor;
}

N.B. I use 10 positions here as this is smaller than the 15 (and some) positions of max integer in JavaScript, it results in a number bigger than 97 and it's a nice round number. The first two arguments matter.

2 of 6
12

A bunch of improvements to Benedikt's version: cRest += '' + cDivident; is a bugfix; parseInt(divisor) makes it possible to pass both arguments as strings; check for empty string at the end makes it always return numerical values; added var statements so it's not using global variables; converted foreach to old-style for so it works in browsers with older Javascript; fixed the cRest == 0; bug (thanks @Dan.StackOverflow).

function modulo(divident, divisor) {
  let cDivident = '';
  let cRest = '';

  for (let i in divident) {
    let cChar = divident[i];
    let cOperator = cRest + '' + cDivident + '' + cChar;

    if (cOperator < parseInt(divisor)) {
      cDivident += '' + cChar;
    } else {
      cRest = cOperator % divisor;
      if (cRest == 0) {
        cRest = '';
      }
      cDivident = '';
    }
  }
  cRest += '' + cDivident;
  if (cRest == '') {
    cRest = 0;
  }
  return cRest;
}
🌐
Mimo
mimo.org › glossary › javascript › modulo-operator
JavaScript Modulo Operator: Syntax, Usage, and Examples
The modulo operator works with floating point numbers, although precision issues may arise due to how JavaScript handles decimals. ... Here, 5.5 divided by 2 equals 2 with a remainder of 1.5, so the result is 1.5. This can be useful for calculations involving time, distance, or currency when fractional remainders are meaningful.
🌐
Rip Tutorial
riptutorial.com › remainder / modulus (%)
JavaScript Tutorial => Remainder / Modulus (%)
The remainder / modulus operator (%) returns the remainder after (integer) division · This operator returns the remainder left over when one operand is divided by a second operand.
🌐
W3Resource
w3resource.com › javascript-exercises › javascript-math-exercise-46.php
JavaScript Math: Calculate the divisor and modulus of two integers - w3resource
JavaScript exercises, practice and solution: Write a JavaScript function to calculate the divisor and modulus of two integers.