Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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