Created
April 23, 2018 13:49
-
-
Save ravid7000/d44a209f7a87d200188401cf0eb8f29f to your computer and use it in GitHub Desktop.
Find closest number multiple of 10, 100, 1000, 10000,...
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
/* | |
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