Last active
March 23, 2023 17:05
-
-
Save marlun78/13c4803c5d782fef89907b9e2e61c914 to your computer and use it in GitHub Desktop.
A TypeScript implementation of the `mround` function from Google Sheets, Microsoft Excel etc.
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
/** | |
* Rounds one number to the nearest integer multiple of another. | |
* @param value The number to round to the nearest integer multiple of another. | |
* @param factor The number to whose multiples value will be rounded. | |
* @example | |
* mround(10, 3); // 9 | |
* mround(-10, -3); // -9 | |
* mround(5, -2); // Error: Parameters of mround must have same signs (both positive or both negative) | |
*/ | |
export function mround(value: number, factor: number): number { | |
if (Math.abs(value) === 0 || Math.abs(factor) === 0) { | |
return 0; | |
} | |
if (Math.sign(value) !== Math.sign(factor)) { | |
throw new Error('Parameters of mround must have same signs (both positive or both negative).'); | |
} | |
return Math.round(value / factor) * factor; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment