Skip to content

Instantly share code, notes, and snippets.

@tannerhodges
Created January 11, 2016 15:21
Show Gist options
  • Save tannerhodges/4e581eed242fdccb9d19 to your computer and use it in GitHub Desktop.
Save tannerhodges/4e581eed242fdccb9d19 to your computer and use it in GitHub Desktop.
Zero pad a number. Defaults to 2 zeros.
/**
* Zero pad a number. Defaults to 2 zeros. Can optionally pad arbitrary
* lengths and characters.
*
* Based on:
* - "pad a string to get to a determined length?" http://stackoverflow.com/a/14760377/1786459
* - "Repeat Character N Times" http://stackoverflow.com/a/1877479/1786459
*
* @param {Number} num
* @param {Number} length
* @param {String} char
* @return {String}
*/
function pad(num, length, char) {
length = length || 2;
var pad = Array(length).join(char || '0');
return String(pad + num).slice(-1 * length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment