Skip to main content

One post tagged with "modulo"

View All Tags

ยท One min read
Peter Johnson

Javascript currently lacks an IEEE 754 floating-point remainder function.

You'll find no shortage of developers complaining about how broken the Javascript Modulo operator is online.

There's actually a TC39 proposal to improve things.

In the meantime you might like to use this function which is equivalent to the math.Remainder function from the Go stdlib:

/** Computes the IEEE 754 floating-point remainder of x / y. */
const remainder = (x, y) => {
if (isNaN(x) || isNaN(y) || !isFinite(x) || y === 0) return NaN

const quotient = x / y
let n = Math.round(quotient)

// When quotient is exactly halfway between two integers, round to the nearest even integer
if (Math.abs(quotient - n) === 0.5) n = 2 * Math.round(quotient / 2)

const rem = x - n * y
return !rem ? Math.sign(x) * 0 : rem
}
-5 % 3
-2

remainder(-5, 3)
1