Created
July 24, 2024 09:18
-
-
Save missinglink/2940b4f6bc74b465abce279c2d1f2cd3 to your computer and use it in GitHub Desktop.
Javascript IEEE 754 floating-point remainder of x / y
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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