Created
March 16, 2012 14:59
-
-
Save remy/2050437 to your computer and use it in GitHub Desktop.
2 digit pad
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
// a bunch of ways to get from 4 => 04 (whilst maintaining 40 => 40). This would be a pad function for times, hours, mins, seconds. | |
var i = 4; | |
// while | |
while((i+'').length<2)i='0'+i | |
// greater than 9 | |
i=(i>9?i:'0'+i) | |
// regexp | |
i=(i+'').replace(/^(\d{1})$/,"0$1") | |
// substr | |
i='0'.substr(i<10?0:1) | |
// toString :( | |
if(i<10){i="0"+i.toString()}else{i=i.toString()} | |
// slice (works below 99 - good for minutes - which was the point) | |
i=('0'+i).slice(-2) | |
// substr div | |
i='0'.substr(i/10)+i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a minified version of what I use in TempusJS:
1st argument is number, second argument is length of desired string (defaulting to 2), third is the character (defaulting to 0). So you can do:
strpad(4) === "04"
strpad(4, 3) === "004"
strpad(400) === "400"
strpad(4, 2, ' ') === " 4"
strpad(4, 5, 'X') === "XXXX4"