Last active
March 11, 2019 03:59
-
-
Save iconifyit/dfe08be5f9103a3acb91c5945e24d59a to your computer and use it in GitHub Desktop.
Pad an integer with X number of zeroes
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
/** | |
* Add leading zeroes to an integer. | |
* @param {int} num The number to which to add leading zeros. | |
* @param {ing} zeros The length of the resulting string. | |
* @returns {str} | |
*/ | |
function addLeadingZeros(num, width) { | |
return String(Math.pow(10, width) + num).slice(-width) ; | |
} | |
// Examples | |
console.log( addLeadingZeros( 21, 3 ); // returns "021" | |
console.log( addLeadingZeros( 7, 2 ); // returns "07" | |
console.log( addLeadingZeros( 4, 6); // returns "000004" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment