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 |
Hi,
Do you know jsperf.com ? I create a testcase here http://jsperf.com/a-bunch-of-ways-to-get-from-4-04
Hope it helps?
@Rem Ah, I didn’t know it was a requirement that this should still work for three-digit numbers (the title of this gist is “2 digit pad” which suggests otherwise). Fair enough.
"substr" should have +i at the end
Quite a speed difference between them
http://jsperf.com/pad-via-remy-sharp
Here is a minified version of what I use in TempusJS:
function strpad(s,w,c){w=w||2;w-=(s=""+s).length;return(0<w?Array(w+1).join(c||0):"")+s}
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"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mathiasbynens - cheers, fixed. That .slice(-2) doesn't work beyond 99. That said, if you're padding minutes, then it's viable.