Skip to content

Instantly share code, notes, and snippets.

@ravid7000
Created April 23, 2018 13:49
Show Gist options
  • Save ravid7000/d44a209f7a87d200188401cf0eb8f29f to your computer and use it in GitHub Desktop.
Save ravid7000/d44a209f7a87d200188401cf0eb8f29f to your computer and use it in GitHub Desktop.
Find closest number multiple of 10, 100, 1000, 10000,...
/*
ceilToNearest(5)
> 10
*/
function ceilToNearest(num) {
let len = Math.ceil(Math.log10(Math.abs(num) + 1))
let divisor = Math.pow(10, (len - 1) === 0 ? 1 : (len - 1))
if (num % divisor > 0) {
return (Math.round(num / divisor) + 1) * divisor
}
return Math.round(num / divisor) * divisor
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment