Skip to content

Instantly share code, notes, and snippets.

@remy
Created March 16, 2012 14:59
Show Gist options
  • Save remy/2050437 to your computer and use it in GitHub Desktop.
Save remy/2050437 to your computer and use it in GitHub Desktop.
2 digit pad
// 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
@Hugosslade
Copy link

Anything ternary with <10 can be swapped to be >9 and the internals swapped

@remy
Copy link
Author

remy commented Mar 16, 2012

@mathiasbynens - cheers, fixed. That .slice(-2) doesn't work beyond 99. That said, if you're padding minutes, then it's viable.

@jfreyre
Copy link

jfreyre commented Mar 16, 2012

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?

@mathiasbynens
Copy link

@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.

@maug
Copy link

maug commented Mar 16, 2012

"substr" should have +i at the end

@adambankin
Copy link

Quite a speed difference between them
http://jsperf.com/pad-via-remy-sharp

@keithamus
Copy link

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