Skip to content

Instantly share code, notes, and snippets.

@mhairston
Created May 3, 2022 20:18
Show Gist options
  • Save mhairston/f161119c2a7535f40c2b2d04a5dc15f0 to your computer and use it in GitHub Desktop.
Save mhairston/f161119c2a7535f40c2b2d04a5dc15f0 to your computer and use it in GitHub Desktop.
Quantize value to a multiple
/**
* Return a number "rounded" to the nearest multiple of `amount`.
*
* @param {number} num - The number to quantize
* @param {number} amount - the quantization factor
* @return {number} The multiple of `amount` that is nearest to `number`.
*/
quantize(num, amount) {
const halfway = Math.round(amount / 2);
if (amount == 1) {
return Math.round(amount);
}
return num - (num % amount) + halfway;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment