Skip to content

Instantly share code, notes, and snippets.

@pistou
Last active January 21, 2021 14:10
Show Gist options
  • Save pistou/1a1d31afe47e9f537f9f2893866c13d8 to your computer and use it in GitHub Desktop.
Save pistou/1a1d31afe47e9f537f9f2893866c13d8 to your computer and use it in GitHub Desktop.
Round number to closest power of X
function roundToPow(n, pow = 10) {
const p = Math.pow(pow, Math.round(n).toString().length - 1);
return Math.round(n / p) * p;
}
console.log(roundToPow(997)); // 1000
console.log(roundToPow(12457)); // 10000
console.log(roundToPow(13,3)); // 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment