Skip to content

Instantly share code, notes, and snippets.

@iconifyit
Last active March 11, 2019 03:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iconifyit/dfe08be5f9103a3acb91c5945e24d59a to your computer and use it in GitHub Desktop.
Save iconifyit/dfe08be5f9103a3acb91c5945e24d59a to your computer and use it in GitHub Desktop.
Pad an integer with X number of zeroes
/**
* 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