Syntax Atlas

Python Modulo With Negative Numbers, Measured

What % returns for negative numbers in Python, next to what the same expression returns in JavaScript — measured on our own computer.

What we measured: Linux x86_64 (kernel 7.0.0-34-generic), CPython 3.12.13 and CPython 3.14.4, Node.js v20.20.2, on the 10 input pairs below. Not measured: Windows and macOS, browser JavaScript engines, PyPy, other Python and Node.js versions, and other languages.

Measured results

Each value is what the interpreter printed: Python shows repr() of the result, JavaScript shows the result with negative zero written as -0; an error shows its exception name. Both CPython versions returned the same value in every cell, so the Python columns are shown once.

The same expression in both languages: a % b

a, bPythonJavaScript
7, 311
-7, 32-1
7, -3-21
-7, -3-1-1
-6, 30-0
6, -300
7.5, 21.51.5
-7.5, 20.5-1.5
-1e-100, 1e1001e+100-1e-100
5, 0ZeroDivisionErrorNaN

Python: floor division, math.fmod and divmod

a, ba // bmath.fmod(a, b)divmod(a, b)
7, 321.0(2, 1)
-7, 3-3-1.0(-3, 2)
7, -3-31.0(-3, -2)
-7, -32-1.0(2, -1)
-6, 3-2-0.0(-2, 0)
6, -3-20.0(-2, 0)
7.5, 23.01.5(3.0, 1.5)
-7.5, 2-4.0-1.5(-4.0, 0.5)
-1e-100, 1e100-1.0-1e-100(-1.0, 1e+100)
5, 0ZeroDivisionErrorValueErrorZeroDivisionError

JavaScript: Math.trunc(a / b) and ((a % b) + b) % b

a, bMath.trunc(a / b)((a % b) + b) % b
7, 321
-7, 3-22
7, -3-2-2
-7, -32-1
-6, 3-20
6, -3-2-0
7.5, 231.5
-7.5, 2-30.5
-1e-100, 1e100-00
5, 0InfinityNaN

What the measurement shows

The JavaScript expression ((a % b) + b) % b

We ran this expression on the same pairs and compared it with Python’s a % b:

What the Python documentation says

“The modulo operator always yields a result with the same sign as its second operand (or zero)”

The Python Language Reference, “Expressions” — Binary arithmetic operations (saved 2026-11-16)

“A zero right argument raises the ZeroDivisionError exception.”

The Python Language Reference, “Expressions” — Binary arithmetic operations (saved 2026-11-16)

“Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments.”

Python Standard Library, “math” — math.fmod (saved 2026-11-16)

JavaScript’s rule is defined in the ECMAScript specification, Number::remainder; we link to it and do not quote it.

From the source pages: “© Copyright 2001 Python Software Foundation. This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.” License texts: History and License (Python Software Foundation License Version 2; Zero Clause BSD License).