Skip to content

Instantly share code, notes, and snippets.

@missinglink
Created July 24, 2024 09:18
Show Gist options
  • Save missinglink/2940b4f6bc74b465abce279c2d1f2cd3 to your computer and use it in GitHub Desktop.
Save missinglink/2940b4f6bc74b465abce279c2d1f2cd3 to your computer and use it in GitHub Desktop.
Javascript IEEE 754 floating-point remainder of x / y
/** Computes the IEEE 754 floating-point remainder of x / y. */
export const remainder = (x: number, y: number): number => {
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment