Skip to content

Instantly share code, notes, and snippets.

@doctyper
Created September 12, 2011 21:46
Show Gist options
  • Save doctyper/1212559 to your computer and use it in GitHub Desktop.
Save doctyper/1212559 to your computer and use it in GitHub Desktop.
Add a leading zero to a single-digit number
// 12 => 12
// 1 => 01
number = ("0" + number).slice(-2);
@potench
Copy link

potench commented Sep 12, 2011

// leading zeros ( good for score keepers? )
// (12,1) => 12,   (12,2) => 12,   (12,3) => 012
// (1,5) => 00001

function leadingZeros(number,howManyZeros) {
    var numStr = number.toString();
    for(var i = 1; i < howManyZeros; i++) {
        if(number < Math.pow(10,i)) {
            numStr = "0" + numStr;
        }
    }
    return numStr;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment