How can I pad a value with leading zeros?











up vote
301
down vote

favorite
87












What is the recommended way to zerofill a value in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I'm wondering if there is a more direct way to do this?



Note: By "zerofilled" I mean it in the database sense of the word (where a 6-digit zerofilled representation of the number 5 would be "000005").










share|improve this question
























  • This really isn't enough information to answer. The most common instance of "zero padding" is probably probably prepending zeroes onto dates: 5/1/2008 > 05/01/2008. Is that what you mean?
    – Triptych
    Aug 12 '09 at 16:38






  • 5




    For node apps, use npm install sprintf-js, and require it in the file you need: sprintf('%0d6', 5);
    – Droogans
    Nov 12 '14 at 19:27










  • function padWithZeroes(n, width) { while(n.length<width) n = '0' + n; return n;} ...assuming n not negative
    – Paolo
    Feb 18 '16 at 23:52












  • @Paolo that function doesn't work if n is numeric. You'd need to convert n to a String before the while in order to access n.length
    – Nick F
    Jun 3 '16 at 10:28












  • @NickF of course... and assuming 'n' is a string.
    – Paolo
    Jun 3 '16 at 10:46















up vote
301
down vote

favorite
87












What is the recommended way to zerofill a value in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I'm wondering if there is a more direct way to do this?



Note: By "zerofilled" I mean it in the database sense of the word (where a 6-digit zerofilled representation of the number 5 would be "000005").










share|improve this question
























  • This really isn't enough information to answer. The most common instance of "zero padding" is probably probably prepending zeroes onto dates: 5/1/2008 > 05/01/2008. Is that what you mean?
    – Triptych
    Aug 12 '09 at 16:38






  • 5




    For node apps, use npm install sprintf-js, and require it in the file you need: sprintf('%0d6', 5);
    – Droogans
    Nov 12 '14 at 19:27










  • function padWithZeroes(n, width) { while(n.length<width) n = '0' + n; return n;} ...assuming n not negative
    – Paolo
    Feb 18 '16 at 23:52












  • @Paolo that function doesn't work if n is numeric. You'd need to convert n to a String before the while in order to access n.length
    – Nick F
    Jun 3 '16 at 10:28












  • @NickF of course... and assuming 'n' is a string.
    – Paolo
    Jun 3 '16 at 10:46













up vote
301
down vote

favorite
87









up vote
301
down vote

favorite
87






87





What is the recommended way to zerofill a value in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I'm wondering if there is a more direct way to do this?



Note: By "zerofilled" I mean it in the database sense of the word (where a 6-digit zerofilled representation of the number 5 would be "000005").










share|improve this question















What is the recommended way to zerofill a value in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I'm wondering if there is a more direct way to do this?



Note: By "zerofilled" I mean it in the database sense of the word (where a 6-digit zerofilled representation of the number 5 would be "000005").







javascript zerofill






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 27 '17 at 13:16


























community wiki





4 revs, 3 users 100%
Wilco













  • This really isn't enough information to answer. The most common instance of "zero padding" is probably probably prepending zeroes onto dates: 5/1/2008 > 05/01/2008. Is that what you mean?
    – Triptych
    Aug 12 '09 at 16:38






  • 5




    For node apps, use npm install sprintf-js, and require it in the file you need: sprintf('%0d6', 5);
    – Droogans
    Nov 12 '14 at 19:27










  • function padWithZeroes(n, width) { while(n.length<width) n = '0' + n; return n;} ...assuming n not negative
    – Paolo
    Feb 18 '16 at 23:52












  • @Paolo that function doesn't work if n is numeric. You'd need to convert n to a String before the while in order to access n.length
    – Nick F
    Jun 3 '16 at 10:28












  • @NickF of course... and assuming 'n' is a string.
    – Paolo
    Jun 3 '16 at 10:46


















  • This really isn't enough information to answer. The most common instance of "zero padding" is probably probably prepending zeroes onto dates: 5/1/2008 > 05/01/2008. Is that what you mean?
    – Triptych
    Aug 12 '09 at 16:38






  • 5




    For node apps, use npm install sprintf-js, and require it in the file you need: sprintf('%0d6', 5);
    – Droogans
    Nov 12 '14 at 19:27










  • function padWithZeroes(n, width) { while(n.length<width) n = '0' + n; return n;} ...assuming n not negative
    – Paolo
    Feb 18 '16 at 23:52












  • @Paolo that function doesn't work if n is numeric. You'd need to convert n to a String before the while in order to access n.length
    – Nick F
    Jun 3 '16 at 10:28












  • @NickF of course... and assuming 'n' is a string.
    – Paolo
    Jun 3 '16 at 10:46
















This really isn't enough information to answer. The most common instance of "zero padding" is probably probably prepending zeroes onto dates: 5/1/2008 > 05/01/2008. Is that what you mean?
– Triptych
Aug 12 '09 at 16:38




This really isn't enough information to answer. The most common instance of "zero padding" is probably probably prepending zeroes onto dates: 5/1/2008 > 05/01/2008. Is that what you mean?
– Triptych
Aug 12 '09 at 16:38




5




5




For node apps, use npm install sprintf-js, and require it in the file you need: sprintf('%0d6', 5);
– Droogans
Nov 12 '14 at 19:27




For node apps, use npm install sprintf-js, and require it in the file you need: sprintf('%0d6', 5);
– Droogans
Nov 12 '14 at 19:27












function padWithZeroes(n, width) { while(n.length<width) n = '0' + n; return n;} ...assuming n not negative
– Paolo
Feb 18 '16 at 23:52






function padWithZeroes(n, width) { while(n.length<width) n = '0' + n; return n;} ...assuming n not negative
– Paolo
Feb 18 '16 at 23:52














@Paolo that function doesn't work if n is numeric. You'd need to convert n to a String before the while in order to access n.length
– Nick F
Jun 3 '16 at 10:28






@Paolo that function doesn't work if n is numeric. You'd need to convert n to a String before the while in order to access n.length
– Nick F
Jun 3 '16 at 10:28














@NickF of course... and assuming 'n' is a string.
– Paolo
Jun 3 '16 at 10:46




@NickF of course... and assuming 'n' is a string.
– Paolo
Jun 3 '16 at 10:46












68 Answers
68






active

oldest

votes













1 2
3
next











up vote
172
down vote



accepted











Note to readers!



As commenters have pointed out, this solution is "clever", and as
clever solutions often are, it's memory intensive and relatively
slow. If performance is a concern for you, don't use this solution!



Potentially outdated: ECMAScript 2017 includes String.prototype.padStart and Number.prototype.toLocaleString is there since ECMAScript 3.1. Example:



var n=-0.1;
n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false})


...will output "-0000.10".



// or 
const padded = (.1+"").padStart(6,"0");
`-${padded}`


...will output "-0000.1".




A simple function is all you need



function zeroFill( number, width )
{
width -= number.toString().length;
if ( width > 0 )
{
return new Array( width + (/./.test( number ) ? 2 : 1) ).join( '0' ) + number;
}
return number + ""; // always return a string
}


you could bake this into a library if you want to conserve namespace or whatever. Like with jQuery's extend.






share|improve this answer



















  • 1




    Now you just need to take care of numbers like 50.1234 and you've got a readable version of my solution below! I did, however, assume that we were just left padding, not overall padding.
    – coderjoe
    Aug 12 '09 at 20:16






  • 5




    Not a fan of creating a new array each time you want to pad a value. Readers should be aware of the the potential memory and GC impact if they're doing large #'s of these (e.g. on a node.js server that's doing 1000's of these operations per second. @profitehlolz's answer would seem to be the better solution.)
    – broofa
    Sep 24 '12 at 12:21






  • 6




    This does not work for negative values: zeroFill(-10, 7) -> "0000-10"
    – digitalbath
    Nov 7 '12 at 15:20






  • 2




    Performance measure amongst three top answers here: jsperf.com/left-zero-pad
    – tomsmeding
    Feb 21 '14 at 16:35






  • 8




    As of ECMAScript 2017, there's a build-in function padStart.
    – Tomas Nikodym
    Sep 11 '16 at 21:23


















up vote
277
down vote













Simple way. You could add string multiplication for the pad and turn it into a function.



var pad = "000000";
var n = '5';
var result = (pad+n).slice(-pad.length);


As a function,



function paddy(num, padlen, padchar) {
var pad_char = typeof padchar !== 'undefined' ? padchar : '0';
var pad = new Array(1 + padlen).join(pad_char);
return (pad + num).slice(-pad.length);
}
var fu = paddy(14, 5); // 00014
var bar = paddy(2, 4, '#'); // ###2





share|improve this answer



















  • 84




    This is a very nice solution, best I've seen. For clarity, here's a simpler version I'm using to pad the minutes in time formatting: ('0'+minutes).slice(-2)
    – Luke Ehresman
    Sep 14 '12 at 0:22








  • 14




    This is 5 times slower than the implementation with a while loop: gist.github.com/4382935
    – andrewrk
    Dec 26 '12 at 20:37






  • 36




    This has a FATAL FLAW with larger than expected numbers -- which is an extremely common occurrence. For example, paddy (888, 2) yields 88 and not 888 as required. This answer also does not handle negative numbers.
    – Brock Adams
    Jun 15 '13 at 22:20








  • 7




    @BrockAdams, zerofill is typically used for fixed width number/formatting cases -- therefore I think it'd actually be less likely (or even a non-issue) if given a 3 digit number when trying to do 2 digit zerofill.
    – Seaux
    Dec 8 '13 at 23:15






  • 7




    Performance measure amongst three top answers here: jsperf.com/left-zero-pad
    – tomsmeding
    Feb 21 '14 at 16:36


















up vote
228
down vote













I can't believe all the complex answers on here... Just use this:



var zerofilled = ('0000'+n).slice(-4);





share|improve this answer



















  • 17




    Good except for negative numbers and numbers longer than 4 digits.
    – wberry
    Sep 19 '14 at 22:40








  • 7




    @wberry this was not intended to be production ready code, but more a simple explanation of the basics to solving the question at hand. Aka it's very easy to determine if a number is positive or negative and add the appropriate sign if needed, so i didn't want to cluster my easy example with that. Also, it's just as easy to make a function taking a digit length as an arg and using that instead of my hardcoded values.
    – Seaux
    Sep 21 '14 at 4:13






  • 4




    This seems like a good solution for simple cases. Easier to understand.
    – Artur Carvalho
    Jan 28 '15 at 12:23






  • 2




    @OmShankar by "complex answers", I wasn't referring to explained or detailed answers (which are obviously encouraged on this site even though my answer isn't), but rather answers that contained unnecessary code complexity.
    – Seaux
    Aug 10 '15 at 23:10






  • 3




    I like this answer. In my own specific case, I know that the numbers are always positive and never more than 3 digits, and this is often the case when you're padding with leading 0's and your input is well known. Nice!
    – Patrick Chu
    Dec 16 '16 at 22:12


















up vote
104
down vote













I actually had to come up with something like this recently.
I figured there had to be a way to do it without using loops.



This is what I came up with.



function zeroPad(num, numZeros) {
var n = Math.abs(num);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( num < 0 ) {
zeroString = '-' + zeroString;
}

return zeroString+n;
}


Then just use it providing a number to zero pad:



> zeroPad(50,4);
"0050"


If the number is larger than the padding, the number will expand beyond the padding:



> zeroPad(51234, 3);
"51234"


Decimals are fine too!



> zeroPad(51.1234, 4);
"0051.1234"


If you don't mind polluting the global namespace you can add it to Number directly:



Number.prototype.leftZeroPad = function(numZeros) {
var n = Math.abs(this);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( this < 0 ) {
zeroString = '-' + zeroString;
}

return zeroString+n;
}


And if you'd rather have decimals take up space in the padding:



Number.prototype.leftZeroPad = function(numZeros) {
var n = Math.abs(this);
var zeros = Math.max(0, numZeros - n.toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( this < 0 ) {
zeroString = '-' + zeroString;
}

return zeroString+n;
}


Cheers!







XDR came up with a logarithmic variation that seems to perform better.



WARNING: This function fails if num equals zero (e.g. zeropad(0, 2))



function zeroPad (num, numZeros) {
var an = Math.abs (num);
var digitCount = 1 + Math.floor (Math.log (an) / Math.LN10);
if (digitCount >= numZeros) {
return num;
}
var zeroString = Math.pow (10, numZeros - digitCount).toString ().substr (1);
return num < 0 ? '-' + zeroString + an : zeroString + an;
}




Speaking of performance, tomsmeding compared the top 3 answers (4 with the log variation). Guess which one majorly outperformed the other two? :)






share|improve this answer



















  • 9




    This is good, I like how it's readable and robust. The only thing I would change is the name of the numZeros parameter, since it's misleading. It's not the number of zeros you want to add, it's the minimum length the number should be. A better name would be numLength or even length.
    – Senseful
    Jan 2 '12 at 4:23








  • 12




    +1. Unlike the higher voted answers, this one handles negative numbers and does not return gross errors on overflow!!?!
    – Brock Adams
    Jun 15 '13 at 22:39






  • 10




    Performance measure amongst three top answers here: jsperf.com/left-zero-pad
    – tomsmeding
    Feb 21 '14 at 16:36






  • 4




    I improved the performance of this answer by over 100% by using logarithms. Please see the logarithmic test case at http://jsperf.com/left-zero-pad/10
    – XDR
    Aug 18 '14 at 4:30








  • 2




    The original solution is better, logarithmic variation doesn't work if num can be zero...
    – Ondra C.
    Mar 17 '15 at 10:03


















up vote
55
down vote













Here's what I used to pad a number up to 7 characters.



("0000000" + number).slice(-7)


This approach will probably suffice for most people.



Edit: If you want to make it more generic you can do this:



("0".repeat(padding) + number).slice(-padding)





share|improve this answer























  • This fails, badly, on large numbers and negative numbers. number = 123456789, with the code, above, for example.
    – Brock Adams
    Jun 15 '13 at 22:49










  • This solution is the best possible ever for certains scenarios! I've got no clue why we didn't come up with this before. The scenario is: you've got a number which is always positive [as Brock mentioned] and you know that it won't take more characters than your limit. In our case we have a score which we store in Amazon SDB. As you know SDB can't compare numbers, so all scores have to be zero padded. This is extremely easy and effective!
    – Krystian
    Oct 10 '13 at 11:27






  • 2




    Apologies, I should have mentioned that this won't work for negative numbers. I think this deals with the more common positive number case, though. It does what I need, at least!
    – chetbox
    Oct 16 '13 at 11:33










  • Needed this again and realised you don't need new String. You can just use string literals.
    – chetbox
    Mar 4 '16 at 15:56






  • 2




    (new Array(padding + 1).join("0") can be replaced with "0".repeat(padding)
    – Pavel
    Jun 22 '17 at 16:17




















up vote
23
down vote













Unfortunately, there are a lot of needless complicated suggestions for this problem, typically involving writing your own function to do math or string manipulation or calling a third-party utility. However, there is a standard way of doing this in the base JavaScript library with just one line of code. It might be worth wrapping this one line of code in a function to avoid having to specify parameters that you never want to change like the local name or style.



var amount = 5;

var text = amount.toLocaleString('en-US',
{
style: 'decimal',
minimumIntegerDigits: 3,
useGrouping: false
});


This will produce the value of "005" for text. You can also use the toLocaleString function of Number to pad zeros to the right side of the decimal point.



var amount = 5;

var text = amount.toLocaleString('en-US',
{
style: 'decimal',
minimumFractionDigits: 2,
useGrouping: false
});


This will produce the value of "5.00" for text. Change useGrouping to true to use comma separators for thousands.



Note that using toLocaleString() with locales and options arguments is standardized separately in ECMA-402, not in ECMAScript. As of today, some browsers only implement basic support, i.e. toLocaleString() may ignore any arguments.



Complete Example






share|improve this answer























  • Wow, this is a super clean solution and works in node.js.
    – jishi
    Feb 6 '16 at 22:21










  • I chuckled when I read the intro -- "needless complicated suggestions". Software development, as in all engineering disciplines, involves weighing trade-offs. I tried this "standard way" myself -- and timed it. It definitely works, but I would never choose to use it for any kind of repetitive application due to how slow it is compared to many of the other "home rolled" solutions.
    – bearvarine
    Sep 16 '17 at 20:47












  • True, a lot of built-in JavaScript functions perform poorly when looping over lots of data, but I would argue you should not use JavaScript for that, even server-side like Node.js. If you have lots of data to process server-side, you should use a better platform like .NET or Java. If you are processing client-side data for display to the end user, you should only process the data for what you are currently rendering to the end user's screen. For example, render only the visible rows of a table and don't process data for other roads.
    – Daniel Barbalace
    Jul 23 at 21:03




















up vote
20
down vote













If the fill number is known in advance not to exceed a certain value, there's another way to do this with no loops:



var fillZeroes = "00000000000000000000";  // max number of zero fill ever asked for in global

function zeroFill(number, width) {
// make sure it's a string
var input = number + "";
var prefix = "";
if (input.charAt(0) === '-') {
prefix = "-";
input = input.slice(1);
--width;
}
var fillAmt = Math.max(width - input.length, 0);
return prefix + fillZeroes.slice(0, fillAmt) + input;
}


Test cases here: http://jsfiddle.net/jfriend00/N87mZ/






share|improve this answer























  • @BrockAdams - fixed for both cases you mention. If the number is already as wide as the fill width, then no fill is added.
    – jfriend00
    Jun 16 '13 at 1:08












  • Thanks; +1. The negative numbers are slightly off from the usual convention, though. In your test case, -88 should yield "-00088", for example.
    – Brock Adams
    Jun 16 '13 at 1:57








  • 1




    @BrockAdams - I wasn't sure whether calling zeroFill(-88, 5) should produce -00088 or -0088? I guess it depends upon whether you want the width argument to be the entire width of the number or just the number of digits (not including the negative sign). An implementer can easily switch the behavior to not include the negative sign by just removing the --width line of code.
    – jfriend00
    Jun 16 '13 at 3:07




















up vote
18
down vote













In a proposed (stage 3) ES2017 method .padStart() you can simply now do (when implemented/supported):



string.padStart(maxLength, "0"); //max length is the max string length, not max # of fills





share|improve this answer























  • I've been looking for this one for some time now. Thank you for giving some visibility. I hope in 2030 we have it working.
    – dinigo
    Jun 20 '17 at 10:55






  • 1




    Its works now @dinigo ^^ it is live
    – Paulo Roberto
    Nov 22 '17 at 12:47










  • yep, I've used it a couple of times
    – dinigo
    Nov 22 '17 at 13:02


















up vote
17
down vote













The quick and dirty way:



y = (new Array(count + 1 - x.toString().length)).join('0') + x;


For x = 5 and count = 6 you'll have y = "000005"






share|improve this answer



















  • 1




    I got y="0005" with the above, y = (new Array(count + 1 - x.toString().length)).join('0') + x; is what gave me y="000005"
    – forforf
    May 23 '12 at 15:30










  • @forforf thanks, corrected it now!
    – Johann Philipp Strathausen
    May 24 '12 at 22:48










  • Thanks. I always like the shortest code solution.
    – Orr Siloni
    Nov 12 '12 at 14:08






  • 3




    @OrrSiloni: the shortest code solution is actually ('0000'+n).slice(-4)
    – Seaux
    Dec 8 '13 at 23:17




















up vote
12
down vote













Here's a quick function I came up with to do the job. If anyone has a simpler approach, feel free to share!



function zerofill(number, length) {
// Setup
var result = number.toString();
var pad = length - result.length;

while(pad > 0) {
result = '0' + result;
pad--;
}

return result;
}





share|improve this answer























  • I don't think there will be a "simpler" solution - it will always be a function of some sort. We could have a algorithm discussion, but at the end of the day, you'll still end up with a function that zerofills a number.
    – Peter Bailey
    Aug 12 '09 at 17:54










  • My general advice is to use "for" loops as they are generally more stable and faster in ECMAScript languages (ActionScript 1-3, and JavaScript)
    – cwallenpoole
    Aug 12 '09 at 18:03










  • Or, skip iteration altogether ;)
    – Peter Bailey
    Aug 12 '09 at 20:05










  • Simpler function? Probably not. One that doesn't loop? That is possible... though the algorithm isn't entirely trivial.
    – coderjoe
    Aug 12 '09 at 20:09






  • 1




    Wow, pretty much all the above comments are incorrect. @profitehlolz's solution is simpler and suitable for inlining (doesn't need to be a function). Meanwhile, for .vs. while performance is not different enough to be interesting: jsperf.com/fors-vs-while/34
    – broofa
    Sep 24 '12 at 12:07




















up vote
11
down vote













Late to the party here, but I often use this construct for doing ad-hoc padding of some value n, known to be a positive, decimal:



(offset + n + '').substr(1);


Where offset is 10^^digits.



E.g. Padding to 5 digits, where n = 123:



(1e5 + 123 + '').substr(1); // => 00123


The hexidecimal version of this is slightly more verbose:



(0x100000 + 0x123).toString(16).substr(1); // => 00123


Note 1: I like @profitehlolz's solution as well, which is the string version of this, using slice()'s nifty negative-index feature.






share|improve this answer























  • Very elegant and neat!
    – Marc
    Feb 13 '13 at 9:42


















up vote
11
down vote













I really don't know why, but no one did it in the most obvious way. Here it's my implementation.



Function:



/** Pad a number with 0 on the left */
function zeroPad(number, digits) {
var num = number+"";
while(num.length < digits){
num='0'+num;
}
return num;
}


Prototype:



Number.prototype.zeroPad=function(digits){
var num=this+"";
while(num.length < digits){
num='0'+num;
}
return(num);
};


Very straightforward, I can't see any way how this can be any simpler. For some reason I've seem many times here on SO, people just try to avoid 'for' and 'while' loops at any cost. Using regex will probably cost way more cycles for such a trivial 8 digit padding.






share|improve this answer






























    up vote
    9
    down vote













    I use this snipet to get a 5 digits representation



    (value+100000).toString().slice(-5) // "00123" with value=123





    share|improve this answer























    • this is a smart way to add leading zero . I have done something similar to add leading zero for fixed length binary integer
      – Chris.Huang
      May 11 '15 at 2:14


















    up vote
    8
    down vote













    The power of Math!



    x = integer to pad

    y = number of zeroes to pad



    function zeroPad(x, y)
    {
    y = Math.max(y-1,0);
    var n = (x / Math.pow(10,y)).toFixed(y);
    return n.replace('.','');
    }





    share|improve this answer























    • Wow, that is a very clever way to solve this problem. I already had my own solution for this that is exactly functionally equivalent, and even relatively short, but this is concise and probably quite fast.
      – pseudosavant
      Jan 9 '14 at 21:10


















    up vote
    7
    down vote













    First parameter is any real number, second parameter is a positive integer specifying the minimum number of digits to the left of the decimal point and third parameter is an optional positive integer specifying the number if digits to the right of the decimal point.



    function zPad(n, l, r){
    return(a=String(n).match(/(^-?)(d*).?(d*)/))?a[1]+(Array(l).join(0)+a[2]).slice(-Math.max(l,a[2].length))+('undefined'!==typeof r?(0<r?'.':'')+(a[3]+Array(r+1).join(0)).slice(0,r):a[3]?'.'+a[3]:''):0
    }


    so



               zPad(6, 2) === '06'
    zPad(-6, 2) === '-06'
    zPad(600.2, 2) === '600.2'
    zPad(-600, 2) === '-600'
    zPad(6.2, 3) === '006.2'
    zPad(-6.2, 3) === '-006.2'
    zPad(6.2, 3, 0) === '006'
    zPad(6, 2, 3) === '06.000'
    zPad(600.2, 2, 3) === '600.200'
    zPad(-600.1499, 2, 3) === '-600.149'





    share|improve this answer






























      up vote
      7
      down vote













      Don't reinvent the wheel, use underscore string:



      jsFiddle



      var numToPad = '5';

      alert(_.str.pad(numToPad, 6, '0')); // yields: '000005'





      share|improve this answer



















      • 1




        Pure JavaScript! Short and simple, and a jsFiddle example! EXCELLENT! :D
        – tfont
        Oct 10 '14 at 23:41


















      up vote
      7
      down vote













      This is the ES6 solution.






      function pad(num, len) {
      return '0'.repeat(len - num.toString().length) + num;
      }
      alert(pad(1234,6));








      share|improve this answer























      • Clearly the most elegant solution I would just modify it to avoid 2 string conversions: const numStr = String(num) and return '0'.repeat(len - numStr.length) + numStr;
        – ngryman
        Sep 26 '16 at 21:52




















      up vote
      7
      down vote













      I didn't see anyone point out the fact that when you use String.prototype.substr() with a negative number it counts from the right.



      A one liner solution to the OP's question, a 6-digit zerofilled representation of the number 5, is:






      console.log(("00000000" + 5).substr(-6));





      Generalizing we'll get:






      function pad(num, len) { return ("00000000" + num).substr(-len) };

      console.log(pad(5, 6));
      console.log(pad(45, 6));
      console.log(pad(345, 6));
      console.log(pad(2345, 6));
      console.log(pad(12345, 6));








      share|improve this answer























      • nice one liner solution
        – rave
        Sep 21 '17 at 21:06


















      up vote
      6
      down vote













      After a, long, long time of testing 15 different functions/methods found in this questions answers, I now know which is the best (the most versatile and quickest).



      I took 15 functions/methods from the answers to this question and made a script to measure the time taken to execute 100 pads. Each pad would pad the number 9 with 2000 zeros. This may seem excessive, and it is, but it gives you a good idea about the scaling of the functions.



      The code I used can be found here:
      https://gist.github.com/NextToNothing/6325915



      Feel free to modify and test the code yourself.



      In order to get the most versatile method, you have to use a loop. This is because with very large numbers others are likely to fail, whereas, this will succeed.



      So, which loop to use? Well, that would be a while loop. A for loop is still fast, but a while loop is just slightly quicker(a couple of ms) - and cleaner.



      Answers like those by Wilco, Aleksandar Toplek or Vitim.us will do the job perfectly.



      Personally, I tried a different approach. I tried to use a recursive function to pad the string/number. It worked out better than methods joining an array but, still, didn't work as quick as a for loop.



      My function is:



      function pad(str, max, padder) {
      padder = typeof padder === "undefined" ? "0" : padder;
      return str.toString().length < max ? pad(padder.toString() + str, max, padder) : str;
      }


      You can use my function with, or without, setting the padding variable. So like this:



      pad(1, 3); // Returns '001'
      // - Or -
      pad(1, 3, "x"); // Returns 'xx1'


      Personally, after my tests, I would use a method with a while loop, like Aleksandar Toplek or Vitim.us. However, I would modify it slightly so that you are able to set the padding string.



      So, I would use this code:



      function padLeft(str, len, pad) {
      pad = typeof pad === "undefined" ? "0" : pad + "";
      str = str + "";
      while(str.length < len) {
      str = pad + str;
      }
      return str;
      }

      // Usage
      padLeft(1, 3); // Returns '001'
      // - Or -
      padLeft(1, 3, "x"); // Returns 'xx1'


      You could also use it as a prototype function, by using this code:



      Number.prototype.padLeft = function(len, pad) {
      pad = typeof pad === "undefined" ? "0" : pad + "";
      var str = this + "";
      while(str.length < len) {
      str = pad + str;
      }
      return str;
      }

      // Usage
      var num = 1;

      num.padLeft(3); // Returns '001'
      // - Or -
      num.padLeft(3, "x"); // Returns 'xx1'





      share|improve this answer























      • I put this in a jsfiddle to make it quick for others to test, adding your version of the code: jsfiddle.net/kevinmicke/vnvghw7y/2 Your version is always very competitive, and sometimes the fastest. Thanks for the fairly exhaustive testing.
        – kevinmicke
        Oct 5 '15 at 19:17


















      up vote
      6
      down vote













      ECMAScript 2017:
      use padStart or padEnd



      'abc'.padStart(10);         // "       abc"
      'abc'.padStart(10, "foo"); // "foofoofabc"
      'abc'.padStart(6,"123465"); // "123abc"


      More info:





      • https://github.com/tc39/proposal-string-pad-start-end

      • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart






      share|improve this answer























      • Voted up because it works in my scenario and would be nice to have in the specs. (Although it doesn't really answer the question, as it is not about "0"s :-) )
        – Xan-Kun Clark-Davis
        Jun 6 '17 at 9:28




















      up vote
      4
      down vote













      The latest way to do this is much simpler:



      var number = 2
      number.toLocaleString(undefined, {minimumIntegerDigits:2})


      output: "02"






      share|improve this answer























      • (8).toLocaleString(undefined, {minimumIntegerDigits: 5}) returns "00.008" for me, based on my locale.
        – le_m
        Mar 18 '17 at 21:58




















      up vote
      4
      down vote













      Just an another solution, but I think it's more legible.






      function zeroFill(text, size)
      {
      while (text.length < size){
      text = "0" + text;
      }

      return text;
      }








      share|improve this answer























      • Same as which other?
        – Fabio Turati
        Jul 22 '16 at 14:14


















      up vote
      4
      down vote













      In all modern browsers you can use



      numberStr.padStart(numberLength, "0");





      function zeroFill(num, numLength) {
      var numberStr = num.toString();

      return numberStr.padStart(numLength, "0");
      }

      var numbers = [0, 1, 12, 123, 1234, 12345];

      numbers.forEach(
      function(num) {
      var numString = num.toString();

      var paddedNum = zeroFill(numString, 5);

      console.log(paddedNum);
      }
      );





      Here is the MDN reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart






      share|improve this answer






























        up vote
        3
        down vote













        This one is less native, but may be the fastest...



        zeroPad = function (num, count) {
        var pad = (num + '').length - count;
        while(--pad > -1) {
        num = '0' + num;
        }
        return num;
        };





        share|improve this answer























        • i think you want to do pad = count - (num + '').length. negative numbers aren't handled well, but apart from that, it's not bad. +1
          – nickf
          Sep 6 '09 at 23:29


















        up vote
        3
        down vote













        My solution



        Number.prototype.PadLeft = function (length, digit) {
        var str = '' + this;
        while (str.length < length) {
        str = (digit || '0') + str;
        }
        return str;
        };


        Usage



        var a = 567.25;
        a.PadLeft(10); // 0000567.25

        var b = 567.25;
        b.PadLeft(20, '2'); // 22222222222222567.25





        share|improve this answer






























          up vote
          3
          down vote













          Not that this question needs more answers, but I thought I would add the simple lodash version of this.



          _.padLeft(number, 6, '0')






          share|improve this answer



















          • 1




            Better: var zfill = _.partialRight(_.padStart, '0');
            – Droogans
            Mar 14 '16 at 18:03






          • 2




            Some people will probably protest "I don't want to use lodash" but it's hardly a valid argument anymore since you can install only this function: npm install --save lodash.padleft, then import padLeft from 'lodash.padleft' and omit the _.
            – Andy
            Oct 14 '16 at 20:44




















          up vote
          3
          down vote













          Why not use recursion?



          function padZero(s, n) {
          s = s.toString(); // in case someone passes a number
          return s.length >= n ? s : padZero('0' + s, n);
          }





          share|improve this answer























          • padZero(223, 3) fails with '0223'
            – Serginho
            Oct 18 '16 at 10:55










          • Well, I assumed that this function is called with a string as the first parameter. However, I fixed it.
            – lex82
            Oct 18 '16 at 12:12












          • I love recursions :-)
            – Xan-Kun Clark-Davis
            Jun 6 '17 at 9:33


















          up vote
          2
          down vote













          Some monkeypatching also works



          String.prototype.padLeft = function (n, c) {
          if (isNaN(n))
          return null;
          c = c || "0";
          return (new Array(n).join(c).substring(0, this.length-n)) + this;
          };
          var paddedValue = "123".padLeft(6); // returns "000123"
          var otherPadded = "TEXT".padLeft(8, " "); // returns " TEXT"





          share|improve this answer



















          • 1




            -1 monkeypatching the toplevel namespacing in javascript is bad practice.
            – Jeremy Wall
            Sep 7 '09 at 0:37






          • 2




            True for Object and Array objects, but String is not bad
            – Rodrigo
            Sep 11 '09 at 16:56


















          up vote
          2
          down vote













          function pad(toPad, padChar, length){
          return (String(toPad).length < length)
          ? new Array(length - String(toPad).length + 1).join(padChar) + String(toPad)
          : toPad;
          }


          pad(5, 0, 6) = 000005



          pad('10', 0, 2) = 10 // don't pad if not necessary



          pad('S', 'O', 2) = SO



          ...etc.



          Cheers






          share|improve this answer























          • This doesn't work. pad(100, '0', 4) => 000100
            – drewish
            May 22 '12 at 20:23










          • I think it should be more like: var s = String(toPad); return (s.length < length) ? new Array(length - s.length + 1).join('0') + s : s; if you fix it I'll remove my down vote.
            – drewish
            May 22 '12 at 20:24












          • @drewish Thanks for catching that, I agree with your edit (except for the hardcoded 0 join char :) -- Answer updated.
            – Madbreaks
            May 22 '12 at 21:25










          • Ah yeah I'd hard coded it in my usage.
            – drewish
            May 23 '12 at 2:04










          • I think it'd be better to store the string into a temporary variable. I did some benchmarking of that here: jsperf.com/padding-with-memoization it's also got benchmarks for the use of the new in "new Array" the results for new are all over the place but memiozation seems like the way to go.
            – drewish
            May 23 '12 at 16:28


















          up vote
          2
          down vote













          The simplest, most straight-forward solution you will find.



          function zerofill(number,length) {
          var output = number.toString();
          while(output.length < length) {
          output = '0' + output;
          }
          return output;
          }





          share|improve this answer



























            1 2
            3
            next


            protected by Ionică Bizău Dec 2 '14 at 18:19



            Thank you for your interest in this question.
            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



            Would you like to answer one of these unanswered questions instead?














            68 Answers
            68






            active

            oldest

            votes








            68 Answers
            68






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            1 2
            3
            next









            up vote
            172
            down vote



            accepted











            Note to readers!



            As commenters have pointed out, this solution is "clever", and as
            clever solutions often are, it's memory intensive and relatively
            slow. If performance is a concern for you, don't use this solution!



            Potentially outdated: ECMAScript 2017 includes String.prototype.padStart and Number.prototype.toLocaleString is there since ECMAScript 3.1. Example:



            var n=-0.1;
            n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false})


            ...will output "-0000.10".



            // or 
            const padded = (.1+"").padStart(6,"0");
            `-${padded}`


            ...will output "-0000.1".




            A simple function is all you need



            function zeroFill( number, width )
            {
            width -= number.toString().length;
            if ( width > 0 )
            {
            return new Array( width + (/./.test( number ) ? 2 : 1) ).join( '0' ) + number;
            }
            return number + ""; // always return a string
            }


            you could bake this into a library if you want to conserve namespace or whatever. Like with jQuery's extend.






            share|improve this answer



















            • 1




              Now you just need to take care of numbers like 50.1234 and you've got a readable version of my solution below! I did, however, assume that we were just left padding, not overall padding.
              – coderjoe
              Aug 12 '09 at 20:16






            • 5




              Not a fan of creating a new array each time you want to pad a value. Readers should be aware of the the potential memory and GC impact if they're doing large #'s of these (e.g. on a node.js server that's doing 1000's of these operations per second. @profitehlolz's answer would seem to be the better solution.)
              – broofa
              Sep 24 '12 at 12:21






            • 6




              This does not work for negative values: zeroFill(-10, 7) -> "0000-10"
              – digitalbath
              Nov 7 '12 at 15:20






            • 2




              Performance measure amongst three top answers here: jsperf.com/left-zero-pad
              – tomsmeding
              Feb 21 '14 at 16:35






            • 8




              As of ECMAScript 2017, there's a build-in function padStart.
              – Tomas Nikodym
              Sep 11 '16 at 21:23















            up vote
            172
            down vote



            accepted











            Note to readers!



            As commenters have pointed out, this solution is "clever", and as
            clever solutions often are, it's memory intensive and relatively
            slow. If performance is a concern for you, don't use this solution!



            Potentially outdated: ECMAScript 2017 includes String.prototype.padStart and Number.prototype.toLocaleString is there since ECMAScript 3.1. Example:



            var n=-0.1;
            n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false})


            ...will output "-0000.10".



            // or 
            const padded = (.1+"").padStart(6,"0");
            `-${padded}`


            ...will output "-0000.1".




            A simple function is all you need



            function zeroFill( number, width )
            {
            width -= number.toString().length;
            if ( width > 0 )
            {
            return new Array( width + (/./.test( number ) ? 2 : 1) ).join( '0' ) + number;
            }
            return number + ""; // always return a string
            }


            you could bake this into a library if you want to conserve namespace or whatever. Like with jQuery's extend.






            share|improve this answer



















            • 1




              Now you just need to take care of numbers like 50.1234 and you've got a readable version of my solution below! I did, however, assume that we were just left padding, not overall padding.
              – coderjoe
              Aug 12 '09 at 20:16






            • 5




              Not a fan of creating a new array each time you want to pad a value. Readers should be aware of the the potential memory and GC impact if they're doing large #'s of these (e.g. on a node.js server that's doing 1000's of these operations per second. @profitehlolz's answer would seem to be the better solution.)
              – broofa
              Sep 24 '12 at 12:21






            • 6




              This does not work for negative values: zeroFill(-10, 7) -> "0000-10"
              – digitalbath
              Nov 7 '12 at 15:20






            • 2




              Performance measure amongst three top answers here: jsperf.com/left-zero-pad
              – tomsmeding
              Feb 21 '14 at 16:35






            • 8




              As of ECMAScript 2017, there's a build-in function padStart.
              – Tomas Nikodym
              Sep 11 '16 at 21:23













            up vote
            172
            down vote



            accepted







            up vote
            172
            down vote



            accepted







            Note to readers!



            As commenters have pointed out, this solution is "clever", and as
            clever solutions often are, it's memory intensive and relatively
            slow. If performance is a concern for you, don't use this solution!



            Potentially outdated: ECMAScript 2017 includes String.prototype.padStart and Number.prototype.toLocaleString is there since ECMAScript 3.1. Example:



            var n=-0.1;
            n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false})


            ...will output "-0000.10".



            // or 
            const padded = (.1+"").padStart(6,"0");
            `-${padded}`


            ...will output "-0000.1".




            A simple function is all you need



            function zeroFill( number, width )
            {
            width -= number.toString().length;
            if ( width > 0 )
            {
            return new Array( width + (/./.test( number ) ? 2 : 1) ).join( '0' ) + number;
            }
            return number + ""; // always return a string
            }


            you could bake this into a library if you want to conserve namespace or whatever. Like with jQuery's extend.






            share|improve this answer















            Note to readers!



            As commenters have pointed out, this solution is "clever", and as
            clever solutions often are, it's memory intensive and relatively
            slow. If performance is a concern for you, don't use this solution!



            Potentially outdated: ECMAScript 2017 includes String.prototype.padStart and Number.prototype.toLocaleString is there since ECMAScript 3.1. Example:



            var n=-0.1;
            n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false})


            ...will output "-0000.10".



            // or 
            const padded = (.1+"").padStart(6,"0");
            `-${padded}`


            ...will output "-0000.1".




            A simple function is all you need



            function zeroFill( number, width )
            {
            width -= number.toString().length;
            if ( width > 0 )
            {
            return new Array( width + (/./.test( number ) ? 2 : 1) ).join( '0' ) + number;
            }
            return number + ""; // always return a string
            }


            you could bake this into a library if you want to conserve namespace or whatever. Like with jQuery's extend.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Dec 6 '17 at 15:21


























            community wiki





            9 revs, 5 users 66%
            Peter Bailey









            • 1




              Now you just need to take care of numbers like 50.1234 and you've got a readable version of my solution below! I did, however, assume that we were just left padding, not overall padding.
              – coderjoe
              Aug 12 '09 at 20:16






            • 5




              Not a fan of creating a new array each time you want to pad a value. Readers should be aware of the the potential memory and GC impact if they're doing large #'s of these (e.g. on a node.js server that's doing 1000's of these operations per second. @profitehlolz's answer would seem to be the better solution.)
              – broofa
              Sep 24 '12 at 12:21






            • 6




              This does not work for negative values: zeroFill(-10, 7) -> "0000-10"
              – digitalbath
              Nov 7 '12 at 15:20






            • 2




              Performance measure amongst three top answers here: jsperf.com/left-zero-pad
              – tomsmeding
              Feb 21 '14 at 16:35






            • 8




              As of ECMAScript 2017, there's a build-in function padStart.
              – Tomas Nikodym
              Sep 11 '16 at 21:23














            • 1




              Now you just need to take care of numbers like 50.1234 and you've got a readable version of my solution below! I did, however, assume that we were just left padding, not overall padding.
              – coderjoe
              Aug 12 '09 at 20:16






            • 5




              Not a fan of creating a new array each time you want to pad a value. Readers should be aware of the the potential memory and GC impact if they're doing large #'s of these (e.g. on a node.js server that's doing 1000's of these operations per second. @profitehlolz's answer would seem to be the better solution.)
              – broofa
              Sep 24 '12 at 12:21






            • 6




              This does not work for negative values: zeroFill(-10, 7) -> "0000-10"
              – digitalbath
              Nov 7 '12 at 15:20






            • 2




              Performance measure amongst three top answers here: jsperf.com/left-zero-pad
              – tomsmeding
              Feb 21 '14 at 16:35






            • 8




              As of ECMAScript 2017, there's a build-in function padStart.
              – Tomas Nikodym
              Sep 11 '16 at 21:23








            1




            1




            Now you just need to take care of numbers like 50.1234 and you've got a readable version of my solution below! I did, however, assume that we were just left padding, not overall padding.
            – coderjoe
            Aug 12 '09 at 20:16




            Now you just need to take care of numbers like 50.1234 and you've got a readable version of my solution below! I did, however, assume that we were just left padding, not overall padding.
            – coderjoe
            Aug 12 '09 at 20:16




            5




            5




            Not a fan of creating a new array each time you want to pad a value. Readers should be aware of the the potential memory and GC impact if they're doing large #'s of these (e.g. on a node.js server that's doing 1000's of these operations per second. @profitehlolz's answer would seem to be the better solution.)
            – broofa
            Sep 24 '12 at 12:21




            Not a fan of creating a new array each time you want to pad a value. Readers should be aware of the the potential memory and GC impact if they're doing large #'s of these (e.g. on a node.js server that's doing 1000's of these operations per second. @profitehlolz's answer would seem to be the better solution.)
            – broofa
            Sep 24 '12 at 12:21




            6




            6




            This does not work for negative values: zeroFill(-10, 7) -> "0000-10"
            – digitalbath
            Nov 7 '12 at 15:20




            This does not work for negative values: zeroFill(-10, 7) -> "0000-10"
            – digitalbath
            Nov 7 '12 at 15:20




            2




            2




            Performance measure amongst three top answers here: jsperf.com/left-zero-pad
            – tomsmeding
            Feb 21 '14 at 16:35




            Performance measure amongst three top answers here: jsperf.com/left-zero-pad
            – tomsmeding
            Feb 21 '14 at 16:35




            8




            8




            As of ECMAScript 2017, there's a build-in function padStart.
            – Tomas Nikodym
            Sep 11 '16 at 21:23




            As of ECMAScript 2017, there's a build-in function padStart.
            – Tomas Nikodym
            Sep 11 '16 at 21:23












            up vote
            277
            down vote













            Simple way. You could add string multiplication for the pad and turn it into a function.



            var pad = "000000";
            var n = '5';
            var result = (pad+n).slice(-pad.length);


            As a function,



            function paddy(num, padlen, padchar) {
            var pad_char = typeof padchar !== 'undefined' ? padchar : '0';
            var pad = new Array(1 + padlen).join(pad_char);
            return (pad + num).slice(-pad.length);
            }
            var fu = paddy(14, 5); // 00014
            var bar = paddy(2, 4, '#'); // ###2





            share|improve this answer



















            • 84




              This is a very nice solution, best I've seen. For clarity, here's a simpler version I'm using to pad the minutes in time formatting: ('0'+minutes).slice(-2)
              – Luke Ehresman
              Sep 14 '12 at 0:22








            • 14




              This is 5 times slower than the implementation with a while loop: gist.github.com/4382935
              – andrewrk
              Dec 26 '12 at 20:37






            • 36




              This has a FATAL FLAW with larger than expected numbers -- which is an extremely common occurrence. For example, paddy (888, 2) yields 88 and not 888 as required. This answer also does not handle negative numbers.
              – Brock Adams
              Jun 15 '13 at 22:20








            • 7




              @BrockAdams, zerofill is typically used for fixed width number/formatting cases -- therefore I think it'd actually be less likely (or even a non-issue) if given a 3 digit number when trying to do 2 digit zerofill.
              – Seaux
              Dec 8 '13 at 23:15






            • 7




              Performance measure amongst three top answers here: jsperf.com/left-zero-pad
              – tomsmeding
              Feb 21 '14 at 16:36















            up vote
            277
            down vote













            Simple way. You could add string multiplication for the pad and turn it into a function.



            var pad = "000000";
            var n = '5';
            var result = (pad+n).slice(-pad.length);


            As a function,



            function paddy(num, padlen, padchar) {
            var pad_char = typeof padchar !== 'undefined' ? padchar : '0';
            var pad = new Array(1 + padlen).join(pad_char);
            return (pad + num).slice(-pad.length);
            }
            var fu = paddy(14, 5); // 00014
            var bar = paddy(2, 4, '#'); // ###2





            share|improve this answer



















            • 84




              This is a very nice solution, best I've seen. For clarity, here's a simpler version I'm using to pad the minutes in time formatting: ('0'+minutes).slice(-2)
              – Luke Ehresman
              Sep 14 '12 at 0:22








            • 14




              This is 5 times slower than the implementation with a while loop: gist.github.com/4382935
              – andrewrk
              Dec 26 '12 at 20:37






            • 36




              This has a FATAL FLAW with larger than expected numbers -- which is an extremely common occurrence. For example, paddy (888, 2) yields 88 and not 888 as required. This answer also does not handle negative numbers.
              – Brock Adams
              Jun 15 '13 at 22:20








            • 7




              @BrockAdams, zerofill is typically used for fixed width number/formatting cases -- therefore I think it'd actually be less likely (or even a non-issue) if given a 3 digit number when trying to do 2 digit zerofill.
              – Seaux
              Dec 8 '13 at 23:15






            • 7




              Performance measure amongst three top answers here: jsperf.com/left-zero-pad
              – tomsmeding
              Feb 21 '14 at 16:36













            up vote
            277
            down vote










            up vote
            277
            down vote









            Simple way. You could add string multiplication for the pad and turn it into a function.



            var pad = "000000";
            var n = '5';
            var result = (pad+n).slice(-pad.length);


            As a function,



            function paddy(num, padlen, padchar) {
            var pad_char = typeof padchar !== 'undefined' ? padchar : '0';
            var pad = new Array(1 + padlen).join(pad_char);
            return (pad + num).slice(-pad.length);
            }
            var fu = paddy(14, 5); // 00014
            var bar = paddy(2, 4, '#'); // ###2





            share|improve this answer














            Simple way. You could add string multiplication for the pad and turn it into a function.



            var pad = "000000";
            var n = '5';
            var result = (pad+n).slice(-pad.length);


            As a function,



            function paddy(num, padlen, padchar) {
            var pad_char = typeof padchar !== 'undefined' ? padchar : '0';
            var pad = new Array(1 + padlen).join(pad_char);
            return (pad + num).slice(-pad.length);
            }
            var fu = paddy(14, 5); // 00014
            var bar = paddy(2, 4, '#'); // ###2






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 23 at 14:49


























            community wiki





            4 revs, 2 users 83%
            profitehlolz









            • 84




              This is a very nice solution, best I've seen. For clarity, here's a simpler version I'm using to pad the minutes in time formatting: ('0'+minutes).slice(-2)
              – Luke Ehresman
              Sep 14 '12 at 0:22








            • 14




              This is 5 times slower than the implementation with a while loop: gist.github.com/4382935
              – andrewrk
              Dec 26 '12 at 20:37






            • 36




              This has a FATAL FLAW with larger than expected numbers -- which is an extremely common occurrence. For example, paddy (888, 2) yields 88 and not 888 as required. This answer also does not handle negative numbers.
              – Brock Adams
              Jun 15 '13 at 22:20








            • 7




              @BrockAdams, zerofill is typically used for fixed width number/formatting cases -- therefore I think it'd actually be less likely (or even a non-issue) if given a 3 digit number when trying to do 2 digit zerofill.
              – Seaux
              Dec 8 '13 at 23:15






            • 7




              Performance measure amongst three top answers here: jsperf.com/left-zero-pad
              – tomsmeding
              Feb 21 '14 at 16:36














            • 84




              This is a very nice solution, best I've seen. For clarity, here's a simpler version I'm using to pad the minutes in time formatting: ('0'+minutes).slice(-2)
              – Luke Ehresman
              Sep 14 '12 at 0:22








            • 14




              This is 5 times slower than the implementation with a while loop: gist.github.com/4382935
              – andrewrk
              Dec 26 '12 at 20:37






            • 36




              This has a FATAL FLAW with larger than expected numbers -- which is an extremely common occurrence. For example, paddy (888, 2) yields 88 and not 888 as required. This answer also does not handle negative numbers.
              – Brock Adams
              Jun 15 '13 at 22:20








            • 7




              @BrockAdams, zerofill is typically used for fixed width number/formatting cases -- therefore I think it'd actually be less likely (or even a non-issue) if given a 3 digit number when trying to do 2 digit zerofill.
              – Seaux
              Dec 8 '13 at 23:15






            • 7




              Performance measure amongst three top answers here: jsperf.com/left-zero-pad
              – tomsmeding
              Feb 21 '14 at 16:36








            84




            84




            This is a very nice solution, best I've seen. For clarity, here's a simpler version I'm using to pad the minutes in time formatting: ('0'+minutes).slice(-2)
            – Luke Ehresman
            Sep 14 '12 at 0:22






            This is a very nice solution, best I've seen. For clarity, here's a simpler version I'm using to pad the minutes in time formatting: ('0'+minutes).slice(-2)
            – Luke Ehresman
            Sep 14 '12 at 0:22






            14




            14




            This is 5 times slower than the implementation with a while loop: gist.github.com/4382935
            – andrewrk
            Dec 26 '12 at 20:37




            This is 5 times slower than the implementation with a while loop: gist.github.com/4382935
            – andrewrk
            Dec 26 '12 at 20:37




            36




            36




            This has a FATAL FLAW with larger than expected numbers -- which is an extremely common occurrence. For example, paddy (888, 2) yields 88 and not 888 as required. This answer also does not handle negative numbers.
            – Brock Adams
            Jun 15 '13 at 22:20






            This has a FATAL FLAW with larger than expected numbers -- which is an extremely common occurrence. For example, paddy (888, 2) yields 88 and not 888 as required. This answer also does not handle negative numbers.
            – Brock Adams
            Jun 15 '13 at 22:20






            7




            7




            @BrockAdams, zerofill is typically used for fixed width number/formatting cases -- therefore I think it'd actually be less likely (or even a non-issue) if given a 3 digit number when trying to do 2 digit zerofill.
            – Seaux
            Dec 8 '13 at 23:15




            @BrockAdams, zerofill is typically used for fixed width number/formatting cases -- therefore I think it'd actually be less likely (or even a non-issue) if given a 3 digit number when trying to do 2 digit zerofill.
            – Seaux
            Dec 8 '13 at 23:15




            7




            7




            Performance measure amongst three top answers here: jsperf.com/left-zero-pad
            – tomsmeding
            Feb 21 '14 at 16:36




            Performance measure amongst three top answers here: jsperf.com/left-zero-pad
            – tomsmeding
            Feb 21 '14 at 16:36










            up vote
            228
            down vote













            I can't believe all the complex answers on here... Just use this:



            var zerofilled = ('0000'+n).slice(-4);





            share|improve this answer



















            • 17




              Good except for negative numbers and numbers longer than 4 digits.
              – wberry
              Sep 19 '14 at 22:40








            • 7




              @wberry this was not intended to be production ready code, but more a simple explanation of the basics to solving the question at hand. Aka it's very easy to determine if a number is positive or negative and add the appropriate sign if needed, so i didn't want to cluster my easy example with that. Also, it's just as easy to make a function taking a digit length as an arg and using that instead of my hardcoded values.
              – Seaux
              Sep 21 '14 at 4:13






            • 4




              This seems like a good solution for simple cases. Easier to understand.
              – Artur Carvalho
              Jan 28 '15 at 12:23






            • 2




              @OmShankar by "complex answers", I wasn't referring to explained or detailed answers (which are obviously encouraged on this site even though my answer isn't), but rather answers that contained unnecessary code complexity.
              – Seaux
              Aug 10 '15 at 23:10






            • 3




              I like this answer. In my own specific case, I know that the numbers are always positive and never more than 3 digits, and this is often the case when you're padding with leading 0's and your input is well known. Nice!
              – Patrick Chu
              Dec 16 '16 at 22:12















            up vote
            228
            down vote













            I can't believe all the complex answers on here... Just use this:



            var zerofilled = ('0000'+n).slice(-4);





            share|improve this answer



















            • 17




              Good except for negative numbers and numbers longer than 4 digits.
              – wberry
              Sep 19 '14 at 22:40








            • 7




              @wberry this was not intended to be production ready code, but more a simple explanation of the basics to solving the question at hand. Aka it's very easy to determine if a number is positive or negative and add the appropriate sign if needed, so i didn't want to cluster my easy example with that. Also, it's just as easy to make a function taking a digit length as an arg and using that instead of my hardcoded values.
              – Seaux
              Sep 21 '14 at 4:13






            • 4




              This seems like a good solution for simple cases. Easier to understand.
              – Artur Carvalho
              Jan 28 '15 at 12:23






            • 2




              @OmShankar by "complex answers", I wasn't referring to explained or detailed answers (which are obviously encouraged on this site even though my answer isn't), but rather answers that contained unnecessary code complexity.
              – Seaux
              Aug 10 '15 at 23:10






            • 3




              I like this answer. In my own specific case, I know that the numbers are always positive and never more than 3 digits, and this is often the case when you're padding with leading 0's and your input is well known. Nice!
              – Patrick Chu
              Dec 16 '16 at 22:12













            up vote
            228
            down vote










            up vote
            228
            down vote









            I can't believe all the complex answers on here... Just use this:



            var zerofilled = ('0000'+n).slice(-4);





            share|improve this answer














            I can't believe all the complex answers on here... Just use this:



            var zerofilled = ('0000'+n).slice(-4);






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Sep 11 at 7:40


























            community wiki





            2 revs, 2 users 67%
            Seaux









            • 17




              Good except for negative numbers and numbers longer than 4 digits.
              – wberry
              Sep 19 '14 at 22:40








            • 7




              @wberry this was not intended to be production ready code, but more a simple explanation of the basics to solving the question at hand. Aka it's very easy to determine if a number is positive or negative and add the appropriate sign if needed, so i didn't want to cluster my easy example with that. Also, it's just as easy to make a function taking a digit length as an arg and using that instead of my hardcoded values.
              – Seaux
              Sep 21 '14 at 4:13






            • 4




              This seems like a good solution for simple cases. Easier to understand.
              – Artur Carvalho
              Jan 28 '15 at 12:23






            • 2




              @OmShankar by "complex answers", I wasn't referring to explained or detailed answers (which are obviously encouraged on this site even though my answer isn't), but rather answers that contained unnecessary code complexity.
              – Seaux
              Aug 10 '15 at 23:10






            • 3




              I like this answer. In my own specific case, I know that the numbers are always positive and never more than 3 digits, and this is often the case when you're padding with leading 0's and your input is well known. Nice!
              – Patrick Chu
              Dec 16 '16 at 22:12














            • 17




              Good except for negative numbers and numbers longer than 4 digits.
              – wberry
              Sep 19 '14 at 22:40








            • 7




              @wberry this was not intended to be production ready code, but more a simple explanation of the basics to solving the question at hand. Aka it's very easy to determine if a number is positive or negative and add the appropriate sign if needed, so i didn't want to cluster my easy example with that. Also, it's just as easy to make a function taking a digit length as an arg and using that instead of my hardcoded values.
              – Seaux
              Sep 21 '14 at 4:13






            • 4




              This seems like a good solution for simple cases. Easier to understand.
              – Artur Carvalho
              Jan 28 '15 at 12:23






            • 2




              @OmShankar by "complex answers", I wasn't referring to explained or detailed answers (which are obviously encouraged on this site even though my answer isn't), but rather answers that contained unnecessary code complexity.
              – Seaux
              Aug 10 '15 at 23:10






            • 3




              I like this answer. In my own specific case, I know that the numbers are always positive and never more than 3 digits, and this is often the case when you're padding with leading 0's and your input is well known. Nice!
              – Patrick Chu
              Dec 16 '16 at 22:12








            17




            17




            Good except for negative numbers and numbers longer than 4 digits.
            – wberry
            Sep 19 '14 at 22:40






            Good except for negative numbers and numbers longer than 4 digits.
            – wberry
            Sep 19 '14 at 22:40






            7




            7




            @wberry this was not intended to be production ready code, but more a simple explanation of the basics to solving the question at hand. Aka it's very easy to determine if a number is positive or negative and add the appropriate sign if needed, so i didn't want to cluster my easy example with that. Also, it's just as easy to make a function taking a digit length as an arg and using that instead of my hardcoded values.
            – Seaux
            Sep 21 '14 at 4:13




            @wberry this was not intended to be production ready code, but more a simple explanation of the basics to solving the question at hand. Aka it's very easy to determine if a number is positive or negative and add the appropriate sign if needed, so i didn't want to cluster my easy example with that. Also, it's just as easy to make a function taking a digit length as an arg and using that instead of my hardcoded values.
            – Seaux
            Sep 21 '14 at 4:13




            4




            4




            This seems like a good solution for simple cases. Easier to understand.
            – Artur Carvalho
            Jan 28 '15 at 12:23




            This seems like a good solution for simple cases. Easier to understand.
            – Artur Carvalho
            Jan 28 '15 at 12:23




            2




            2




            @OmShankar by "complex answers", I wasn't referring to explained or detailed answers (which are obviously encouraged on this site even though my answer isn't), but rather answers that contained unnecessary code complexity.
            – Seaux
            Aug 10 '15 at 23:10




            @OmShankar by "complex answers", I wasn't referring to explained or detailed answers (which are obviously encouraged on this site even though my answer isn't), but rather answers that contained unnecessary code complexity.
            – Seaux
            Aug 10 '15 at 23:10




            3




            3




            I like this answer. In my own specific case, I know that the numbers are always positive and never more than 3 digits, and this is often the case when you're padding with leading 0's and your input is well known. Nice!
            – Patrick Chu
            Dec 16 '16 at 22:12




            I like this answer. In my own specific case, I know that the numbers are always positive and never more than 3 digits, and this is often the case when you're padding with leading 0's and your input is well known. Nice!
            – Patrick Chu
            Dec 16 '16 at 22:12










            up vote
            104
            down vote













            I actually had to come up with something like this recently.
            I figured there had to be a way to do it without using loops.



            This is what I came up with.



            function zeroPad(num, numZeros) {
            var n = Math.abs(num);
            var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
            var zeroString = Math.pow(10,zeros).toString().substr(1);
            if( num < 0 ) {
            zeroString = '-' + zeroString;
            }

            return zeroString+n;
            }


            Then just use it providing a number to zero pad:



            > zeroPad(50,4);
            "0050"


            If the number is larger than the padding, the number will expand beyond the padding:



            > zeroPad(51234, 3);
            "51234"


            Decimals are fine too!



            > zeroPad(51.1234, 4);
            "0051.1234"


            If you don't mind polluting the global namespace you can add it to Number directly:



            Number.prototype.leftZeroPad = function(numZeros) {
            var n = Math.abs(this);
            var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
            var zeroString = Math.pow(10,zeros).toString().substr(1);
            if( this < 0 ) {
            zeroString = '-' + zeroString;
            }

            return zeroString+n;
            }


            And if you'd rather have decimals take up space in the padding:



            Number.prototype.leftZeroPad = function(numZeros) {
            var n = Math.abs(this);
            var zeros = Math.max(0, numZeros - n.toString().length );
            var zeroString = Math.pow(10,zeros).toString().substr(1);
            if( this < 0 ) {
            zeroString = '-' + zeroString;
            }

            return zeroString+n;
            }


            Cheers!







            XDR came up with a logarithmic variation that seems to perform better.



            WARNING: This function fails if num equals zero (e.g. zeropad(0, 2))



            function zeroPad (num, numZeros) {
            var an = Math.abs (num);
            var digitCount = 1 + Math.floor (Math.log (an) / Math.LN10);
            if (digitCount >= numZeros) {
            return num;
            }
            var zeroString = Math.pow (10, numZeros - digitCount).toString ().substr (1);
            return num < 0 ? '-' + zeroString + an : zeroString + an;
            }




            Speaking of performance, tomsmeding compared the top 3 answers (4 with the log variation). Guess which one majorly outperformed the other two? :)






            share|improve this answer



















            • 9




              This is good, I like how it's readable and robust. The only thing I would change is the name of the numZeros parameter, since it's misleading. It's not the number of zeros you want to add, it's the minimum length the number should be. A better name would be numLength or even length.
              – Senseful
              Jan 2 '12 at 4:23








            • 12




              +1. Unlike the higher voted answers, this one handles negative numbers and does not return gross errors on overflow!!?!
              – Brock Adams
              Jun 15 '13 at 22:39






            • 10




              Performance measure amongst three top answers here: jsperf.com/left-zero-pad
              – tomsmeding
              Feb 21 '14 at 16:36






            • 4




              I improved the performance of this answer by over 100% by using logarithms. Please see the logarithmic test case at http://jsperf.com/left-zero-pad/10
              – XDR
              Aug 18 '14 at 4:30








            • 2




              The original solution is better, logarithmic variation doesn't work if num can be zero...
              – Ondra C.
              Mar 17 '15 at 10:03















            up vote
            104
            down vote













            I actually had to come up with something like this recently.
            I figured there had to be a way to do it without using loops.



            This is what I came up with.



            function zeroPad(num, numZeros) {
            var n = Math.abs(num);
            var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
            var zeroString = Math.pow(10,zeros).toString().substr(1);
            if( num < 0 ) {
            zeroString = '-' + zeroString;
            }

            return zeroString+n;
            }


            Then just use it providing a number to zero pad:



            > zeroPad(50,4);
            "0050"


            If the number is larger than the padding, the number will expand beyond the padding:



            > zeroPad(51234, 3);
            "51234"


            Decimals are fine too!



            > zeroPad(51.1234, 4);
            "0051.1234"


            If you don't mind polluting the global namespace you can add it to Number directly:



            Number.prototype.leftZeroPad = function(numZeros) {
            var n = Math.abs(this);
            var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
            var zeroString = Math.pow(10,zeros).toString().substr(1);
            if( this < 0 ) {
            zeroString = '-' + zeroString;
            }

            return zeroString+n;
            }


            And if you'd rather have decimals take up space in the padding:



            Number.prototype.leftZeroPad = function(numZeros) {
            var n = Math.abs(this);
            var zeros = Math.max(0, numZeros - n.toString().length );
            var zeroString = Math.pow(10,zeros).toString().substr(1);
            if( this < 0 ) {
            zeroString = '-' + zeroString;
            }

            return zeroString+n;
            }


            Cheers!







            XDR came up with a logarithmic variation that seems to perform better.



            WARNING: This function fails if num equals zero (e.g. zeropad(0, 2))



            function zeroPad (num, numZeros) {
            var an = Math.abs (num);
            var digitCount = 1 + Math.floor (Math.log (an) / Math.LN10);
            if (digitCount >= numZeros) {
            return num;
            }
            var zeroString = Math.pow (10, numZeros - digitCount).toString ().substr (1);
            return num < 0 ? '-' + zeroString + an : zeroString + an;
            }




            Speaking of performance, tomsmeding compared the top 3 answers (4 with the log variation). Guess which one majorly outperformed the other two? :)






            share|improve this answer



















            • 9




              This is good, I like how it's readable and robust. The only thing I would change is the name of the numZeros parameter, since it's misleading. It's not the number of zeros you want to add, it's the minimum length the number should be. A better name would be numLength or even length.
              – Senseful
              Jan 2 '12 at 4:23








            • 12




              +1. Unlike the higher voted answers, this one handles negative numbers and does not return gross errors on overflow!!?!
              – Brock Adams
              Jun 15 '13 at 22:39






            • 10




              Performance measure amongst three top answers here: jsperf.com/left-zero-pad
              – tomsmeding
              Feb 21 '14 at 16:36






            • 4




              I improved the performance of this answer by over 100% by using logarithms. Please see the logarithmic test case at http://jsperf.com/left-zero-pad/10
              – XDR
              Aug 18 '14 at 4:30








            • 2




              The original solution is better, logarithmic variation doesn't work if num can be zero...
              – Ondra C.
              Mar 17 '15 at 10:03













            up vote
            104
            down vote










            up vote
            104
            down vote









            I actually had to come up with something like this recently.
            I figured there had to be a way to do it without using loops.



            This is what I came up with.



            function zeroPad(num, numZeros) {
            var n = Math.abs(num);
            var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
            var zeroString = Math.pow(10,zeros).toString().substr(1);
            if( num < 0 ) {
            zeroString = '-' + zeroString;
            }

            return zeroString+n;
            }


            Then just use it providing a number to zero pad:



            > zeroPad(50,4);
            "0050"


            If the number is larger than the padding, the number will expand beyond the padding:



            > zeroPad(51234, 3);
            "51234"


            Decimals are fine too!



            > zeroPad(51.1234, 4);
            "0051.1234"


            If you don't mind polluting the global namespace you can add it to Number directly:



            Number.prototype.leftZeroPad = function(numZeros) {
            var n = Math.abs(this);
            var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
            var zeroString = Math.pow(10,zeros).toString().substr(1);
            if( this < 0 ) {
            zeroString = '-' + zeroString;
            }

            return zeroString+n;
            }


            And if you'd rather have decimals take up space in the padding:



            Number.prototype.leftZeroPad = function(numZeros) {
            var n = Math.abs(this);
            var zeros = Math.max(0, numZeros - n.toString().length );
            var zeroString = Math.pow(10,zeros).toString().substr(1);
            if( this < 0 ) {
            zeroString = '-' + zeroString;
            }

            return zeroString+n;
            }


            Cheers!







            XDR came up with a logarithmic variation that seems to perform better.



            WARNING: This function fails if num equals zero (e.g. zeropad(0, 2))



            function zeroPad (num, numZeros) {
            var an = Math.abs (num);
            var digitCount = 1 + Math.floor (Math.log (an) / Math.LN10);
            if (digitCount >= numZeros) {
            return num;
            }
            var zeroString = Math.pow (10, numZeros - digitCount).toString ().substr (1);
            return num < 0 ? '-' + zeroString + an : zeroString + an;
            }




            Speaking of performance, tomsmeding compared the top 3 answers (4 with the log variation). Guess which one majorly outperformed the other two? :)






            share|improve this answer














            I actually had to come up with something like this recently.
            I figured there had to be a way to do it without using loops.



            This is what I came up with.



            function zeroPad(num, numZeros) {
            var n = Math.abs(num);
            var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
            var zeroString = Math.pow(10,zeros).toString().substr(1);
            if( num < 0 ) {
            zeroString = '-' + zeroString;
            }

            return zeroString+n;
            }


            Then just use it providing a number to zero pad:



            > zeroPad(50,4);
            "0050"


            If the number is larger than the padding, the number will expand beyond the padding:



            > zeroPad(51234, 3);
            "51234"


            Decimals are fine too!



            > zeroPad(51.1234, 4);
            "0051.1234"


            If you don't mind polluting the global namespace you can add it to Number directly:



            Number.prototype.leftZeroPad = function(numZeros) {
            var n = Math.abs(this);
            var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
            var zeroString = Math.pow(10,zeros).toString().substr(1);
            if( this < 0 ) {
            zeroString = '-' + zeroString;
            }

            return zeroString+n;
            }


            And if you'd rather have decimals take up space in the padding:



            Number.prototype.leftZeroPad = function(numZeros) {
            var n = Math.abs(this);
            var zeros = Math.max(0, numZeros - n.toString().length );
            var zeroString = Math.pow(10,zeros).toString().substr(1);
            if( this < 0 ) {
            zeroString = '-' + zeroString;
            }

            return zeroString+n;
            }


            Cheers!







            XDR came up with a logarithmic variation that seems to perform better.



            WARNING: This function fails if num equals zero (e.g. zeropad(0, 2))



            function zeroPad (num, numZeros) {
            var an = Math.abs (num);
            var digitCount = 1 + Math.floor (Math.log (an) / Math.LN10);
            if (digitCount >= numZeros) {
            return num;
            }
            var zeroString = Math.pow (10, numZeros - digitCount).toString ().substr (1);
            return num < 0 ? '-' + zeroString + an : zeroString + an;
            }




            Speaking of performance, tomsmeding compared the top 3 answers (4 with the log variation). Guess which one majorly outperformed the other two? :)







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 23 '17 at 12:34


























            community wiki





            6 revs, 3 users 78%
            coderjoe









            • 9




              This is good, I like how it's readable and robust. The only thing I would change is the name of the numZeros parameter, since it's misleading. It's not the number of zeros you want to add, it's the minimum length the number should be. A better name would be numLength or even length.
              – Senseful
              Jan 2 '12 at 4:23








            • 12




              +1. Unlike the higher voted answers, this one handles negative numbers and does not return gross errors on overflow!!?!
              – Brock Adams
              Jun 15 '13 at 22:39






            • 10




              Performance measure amongst three top answers here: jsperf.com/left-zero-pad
              – tomsmeding
              Feb 21 '14 at 16:36






            • 4




              I improved the performance of this answer by over 100% by using logarithms. Please see the logarithmic test case at http://jsperf.com/left-zero-pad/10
              – XDR
              Aug 18 '14 at 4:30








            • 2




              The original solution is better, logarithmic variation doesn't work if num can be zero...
              – Ondra C.
              Mar 17 '15 at 10:03














            • 9




              This is good, I like how it's readable and robust. The only thing I would change is the name of the numZeros parameter, since it's misleading. It's not the number of zeros you want to add, it's the minimum length the number should be. A better name would be numLength or even length.
              – Senseful
              Jan 2 '12 at 4:23








            • 12




              +1. Unlike the higher voted answers, this one handles negative numbers and does not return gross errors on overflow!!?!
              – Brock Adams
              Jun 15 '13 at 22:39






            • 10




              Performance measure amongst three top answers here: jsperf.com/left-zero-pad
              – tomsmeding
              Feb 21 '14 at 16:36






            • 4




              I improved the performance of this answer by over 100% by using logarithms. Please see the logarithmic test case at http://jsperf.com/left-zero-pad/10
              – XDR
              Aug 18 '14 at 4:30








            • 2




              The original solution is better, logarithmic variation doesn't work if num can be zero...
              – Ondra C.
              Mar 17 '15 at 10:03








            9




            9




            This is good, I like how it's readable and robust. The only thing I would change is the name of the numZeros parameter, since it's misleading. It's not the number of zeros you want to add, it's the minimum length the number should be. A better name would be numLength or even length.
            – Senseful
            Jan 2 '12 at 4:23






            This is good, I like how it's readable and robust. The only thing I would change is the name of the numZeros parameter, since it's misleading. It's not the number of zeros you want to add, it's the minimum length the number should be. A better name would be numLength or even length.
            – Senseful
            Jan 2 '12 at 4:23






            12




            12




            +1. Unlike the higher voted answers, this one handles negative numbers and does not return gross errors on overflow!!?!
            – Brock Adams
            Jun 15 '13 at 22:39




            +1. Unlike the higher voted answers, this one handles negative numbers and does not return gross errors on overflow!!?!
            – Brock Adams
            Jun 15 '13 at 22:39




            10




            10




            Performance measure amongst three top answers here: jsperf.com/left-zero-pad
            – tomsmeding
            Feb 21 '14 at 16:36




            Performance measure amongst three top answers here: jsperf.com/left-zero-pad
            – tomsmeding
            Feb 21 '14 at 16:36




            4




            4




            I improved the performance of this answer by over 100% by using logarithms. Please see the logarithmic test case at http://jsperf.com/left-zero-pad/10
            – XDR
            Aug 18 '14 at 4:30






            I improved the performance of this answer by over 100% by using logarithms. Please see the logarithmic test case at http://jsperf.com/left-zero-pad/10
            – XDR
            Aug 18 '14 at 4:30






            2




            2




            The original solution is better, logarithmic variation doesn't work if num can be zero...
            – Ondra C.
            Mar 17 '15 at 10:03




            The original solution is better, logarithmic variation doesn't work if num can be zero...
            – Ondra C.
            Mar 17 '15 at 10:03










            up vote
            55
            down vote













            Here's what I used to pad a number up to 7 characters.



            ("0000000" + number).slice(-7)


            This approach will probably suffice for most people.



            Edit: If you want to make it more generic you can do this:



            ("0".repeat(padding) + number).slice(-padding)





            share|improve this answer























            • This fails, badly, on large numbers and negative numbers. number = 123456789, with the code, above, for example.
              – Brock Adams
              Jun 15 '13 at 22:49










            • This solution is the best possible ever for certains scenarios! I've got no clue why we didn't come up with this before. The scenario is: you've got a number which is always positive [as Brock mentioned] and you know that it won't take more characters than your limit. In our case we have a score which we store in Amazon SDB. As you know SDB can't compare numbers, so all scores have to be zero padded. This is extremely easy and effective!
              – Krystian
              Oct 10 '13 at 11:27






            • 2




              Apologies, I should have mentioned that this won't work for negative numbers. I think this deals with the more common positive number case, though. It does what I need, at least!
              – chetbox
              Oct 16 '13 at 11:33










            • Needed this again and realised you don't need new String. You can just use string literals.
              – chetbox
              Mar 4 '16 at 15:56






            • 2




              (new Array(padding + 1).join("0") can be replaced with "0".repeat(padding)
              – Pavel
              Jun 22 '17 at 16:17

















            up vote
            55
            down vote













            Here's what I used to pad a number up to 7 characters.



            ("0000000" + number).slice(-7)


            This approach will probably suffice for most people.



            Edit: If you want to make it more generic you can do this:



            ("0".repeat(padding) + number).slice(-padding)





            share|improve this answer























            • This fails, badly, on large numbers and negative numbers. number = 123456789, with the code, above, for example.
              – Brock Adams
              Jun 15 '13 at 22:49










            • This solution is the best possible ever for certains scenarios! I've got no clue why we didn't come up with this before. The scenario is: you've got a number which is always positive [as Brock mentioned] and you know that it won't take more characters than your limit. In our case we have a score which we store in Amazon SDB. As you know SDB can't compare numbers, so all scores have to be zero padded. This is extremely easy and effective!
              – Krystian
              Oct 10 '13 at 11:27






            • 2




              Apologies, I should have mentioned that this won't work for negative numbers. I think this deals with the more common positive number case, though. It does what I need, at least!
              – chetbox
              Oct 16 '13 at 11:33










            • Needed this again and realised you don't need new String. You can just use string literals.
              – chetbox
              Mar 4 '16 at 15:56






            • 2




              (new Array(padding + 1).join("0") can be replaced with "0".repeat(padding)
              – Pavel
              Jun 22 '17 at 16:17















            up vote
            55
            down vote










            up vote
            55
            down vote









            Here's what I used to pad a number up to 7 characters.



            ("0000000" + number).slice(-7)


            This approach will probably suffice for most people.



            Edit: If you want to make it more generic you can do this:



            ("0".repeat(padding) + number).slice(-padding)





            share|improve this answer














            Here's what I used to pad a number up to 7 characters.



            ("0000000" + number).slice(-7)


            This approach will probably suffice for most people.



            Edit: If you want to make it more generic you can do this:



            ("0".repeat(padding) + number).slice(-padding)






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jun 27 '17 at 9:46


























            community wiki





            6 revs
            chetbox













            • This fails, badly, on large numbers and negative numbers. number = 123456789, with the code, above, for example.
              – Brock Adams
              Jun 15 '13 at 22:49










            • This solution is the best possible ever for certains scenarios! I've got no clue why we didn't come up with this before. The scenario is: you've got a number which is always positive [as Brock mentioned] and you know that it won't take more characters than your limit. In our case we have a score which we store in Amazon SDB. As you know SDB can't compare numbers, so all scores have to be zero padded. This is extremely easy and effective!
              – Krystian
              Oct 10 '13 at 11:27






            • 2




              Apologies, I should have mentioned that this won't work for negative numbers. I think this deals with the more common positive number case, though. It does what I need, at least!
              – chetbox
              Oct 16 '13 at 11:33










            • Needed this again and realised you don't need new String. You can just use string literals.
              – chetbox
              Mar 4 '16 at 15:56






            • 2




              (new Array(padding + 1).join("0") can be replaced with "0".repeat(padding)
              – Pavel
              Jun 22 '17 at 16:17




















            • This fails, badly, on large numbers and negative numbers. number = 123456789, with the code, above, for example.
              – Brock Adams
              Jun 15 '13 at 22:49










            • This solution is the best possible ever for certains scenarios! I've got no clue why we didn't come up with this before. The scenario is: you've got a number which is always positive [as Brock mentioned] and you know that it won't take more characters than your limit. In our case we have a score which we store in Amazon SDB. As you know SDB can't compare numbers, so all scores have to be zero padded. This is extremely easy and effective!
              – Krystian
              Oct 10 '13 at 11:27






            • 2




              Apologies, I should have mentioned that this won't work for negative numbers. I think this deals with the more common positive number case, though. It does what I need, at least!
              – chetbox
              Oct 16 '13 at 11:33










            • Needed this again and realised you don't need new String. You can just use string literals.
              – chetbox
              Mar 4 '16 at 15:56






            • 2




              (new Array(padding + 1).join("0") can be replaced with "0".repeat(padding)
              – Pavel
              Jun 22 '17 at 16:17


















            This fails, badly, on large numbers and negative numbers. number = 123456789, with the code, above, for example.
            – Brock Adams
            Jun 15 '13 at 22:49




            This fails, badly, on large numbers and negative numbers. number = 123456789, with the code, above, for example.
            – Brock Adams
            Jun 15 '13 at 22:49












            This solution is the best possible ever for certains scenarios! I've got no clue why we didn't come up with this before. The scenario is: you've got a number which is always positive [as Brock mentioned] and you know that it won't take more characters than your limit. In our case we have a score which we store in Amazon SDB. As you know SDB can't compare numbers, so all scores have to be zero padded. This is extremely easy and effective!
            – Krystian
            Oct 10 '13 at 11:27




            This solution is the best possible ever for certains scenarios! I've got no clue why we didn't come up with this before. The scenario is: you've got a number which is always positive [as Brock mentioned] and you know that it won't take more characters than your limit. In our case we have a score which we store in Amazon SDB. As you know SDB can't compare numbers, so all scores have to be zero padded. This is extremely easy and effective!
            – Krystian
            Oct 10 '13 at 11:27




            2




            2




            Apologies, I should have mentioned that this won't work for negative numbers. I think this deals with the more common positive number case, though. It does what I need, at least!
            – chetbox
            Oct 16 '13 at 11:33




            Apologies, I should have mentioned that this won't work for negative numbers. I think this deals with the more common positive number case, though. It does what I need, at least!
            – chetbox
            Oct 16 '13 at 11:33












            Needed this again and realised you don't need new String. You can just use string literals.
            – chetbox
            Mar 4 '16 at 15:56




            Needed this again and realised you don't need new String. You can just use string literals.
            – chetbox
            Mar 4 '16 at 15:56




            2




            2




            (new Array(padding + 1).join("0") can be replaced with "0".repeat(padding)
            – Pavel
            Jun 22 '17 at 16:17






            (new Array(padding + 1).join("0") can be replaced with "0".repeat(padding)
            – Pavel
            Jun 22 '17 at 16:17












            up vote
            23
            down vote













            Unfortunately, there are a lot of needless complicated suggestions for this problem, typically involving writing your own function to do math or string manipulation or calling a third-party utility. However, there is a standard way of doing this in the base JavaScript library with just one line of code. It might be worth wrapping this one line of code in a function to avoid having to specify parameters that you never want to change like the local name or style.



            var amount = 5;

            var text = amount.toLocaleString('en-US',
            {
            style: 'decimal',
            minimumIntegerDigits: 3,
            useGrouping: false
            });


            This will produce the value of "005" for text. You can also use the toLocaleString function of Number to pad zeros to the right side of the decimal point.



            var amount = 5;

            var text = amount.toLocaleString('en-US',
            {
            style: 'decimal',
            minimumFractionDigits: 2,
            useGrouping: false
            });


            This will produce the value of "5.00" for text. Change useGrouping to true to use comma separators for thousands.



            Note that using toLocaleString() with locales and options arguments is standardized separately in ECMA-402, not in ECMAScript. As of today, some browsers only implement basic support, i.e. toLocaleString() may ignore any arguments.



            Complete Example






            share|improve this answer























            • Wow, this is a super clean solution and works in node.js.
              – jishi
              Feb 6 '16 at 22:21










            • I chuckled when I read the intro -- "needless complicated suggestions". Software development, as in all engineering disciplines, involves weighing trade-offs. I tried this "standard way" myself -- and timed it. It definitely works, but I would never choose to use it for any kind of repetitive application due to how slow it is compared to many of the other "home rolled" solutions.
              – bearvarine
              Sep 16 '17 at 20:47












            • True, a lot of built-in JavaScript functions perform poorly when looping over lots of data, but I would argue you should not use JavaScript for that, even server-side like Node.js. If you have lots of data to process server-side, you should use a better platform like .NET or Java. If you are processing client-side data for display to the end user, you should only process the data for what you are currently rendering to the end user's screen. For example, render only the visible rows of a table and don't process data for other roads.
              – Daniel Barbalace
              Jul 23 at 21:03

















            up vote
            23
            down vote













            Unfortunately, there are a lot of needless complicated suggestions for this problem, typically involving writing your own function to do math or string manipulation or calling a third-party utility. However, there is a standard way of doing this in the base JavaScript library with just one line of code. It might be worth wrapping this one line of code in a function to avoid having to specify parameters that you never want to change like the local name or style.



            var amount = 5;

            var text = amount.toLocaleString('en-US',
            {
            style: 'decimal',
            minimumIntegerDigits: 3,
            useGrouping: false
            });


            This will produce the value of "005" for text. You can also use the toLocaleString function of Number to pad zeros to the right side of the decimal point.



            var amount = 5;

            var text = amount.toLocaleString('en-US',
            {
            style: 'decimal',
            minimumFractionDigits: 2,
            useGrouping: false
            });


            This will produce the value of "5.00" for text. Change useGrouping to true to use comma separators for thousands.



            Note that using toLocaleString() with locales and options arguments is standardized separately in ECMA-402, not in ECMAScript. As of today, some browsers only implement basic support, i.e. toLocaleString() may ignore any arguments.



            Complete Example






            share|improve this answer























            • Wow, this is a super clean solution and works in node.js.
              – jishi
              Feb 6 '16 at 22:21










            • I chuckled when I read the intro -- "needless complicated suggestions". Software development, as in all engineering disciplines, involves weighing trade-offs. I tried this "standard way" myself -- and timed it. It definitely works, but I would never choose to use it for any kind of repetitive application due to how slow it is compared to many of the other "home rolled" solutions.
              – bearvarine
              Sep 16 '17 at 20:47












            • True, a lot of built-in JavaScript functions perform poorly when looping over lots of data, but I would argue you should not use JavaScript for that, even server-side like Node.js. If you have lots of data to process server-side, you should use a better platform like .NET or Java. If you are processing client-side data for display to the end user, you should only process the data for what you are currently rendering to the end user's screen. For example, render only the visible rows of a table and don't process data for other roads.
              – Daniel Barbalace
              Jul 23 at 21:03















            up vote
            23
            down vote










            up vote
            23
            down vote









            Unfortunately, there are a lot of needless complicated suggestions for this problem, typically involving writing your own function to do math or string manipulation or calling a third-party utility. However, there is a standard way of doing this in the base JavaScript library with just one line of code. It might be worth wrapping this one line of code in a function to avoid having to specify parameters that you never want to change like the local name or style.



            var amount = 5;

            var text = amount.toLocaleString('en-US',
            {
            style: 'decimal',
            minimumIntegerDigits: 3,
            useGrouping: false
            });


            This will produce the value of "005" for text. You can also use the toLocaleString function of Number to pad zeros to the right side of the decimal point.



            var amount = 5;

            var text = amount.toLocaleString('en-US',
            {
            style: 'decimal',
            minimumFractionDigits: 2,
            useGrouping: false
            });


            This will produce the value of "5.00" for text. Change useGrouping to true to use comma separators for thousands.



            Note that using toLocaleString() with locales and options arguments is standardized separately in ECMA-402, not in ECMAScript. As of today, some browsers only implement basic support, i.e. toLocaleString() may ignore any arguments.



            Complete Example






            share|improve this answer














            Unfortunately, there are a lot of needless complicated suggestions for this problem, typically involving writing your own function to do math or string manipulation or calling a third-party utility. However, there is a standard way of doing this in the base JavaScript library with just one line of code. It might be worth wrapping this one line of code in a function to avoid having to specify parameters that you never want to change like the local name or style.



            var amount = 5;

            var text = amount.toLocaleString('en-US',
            {
            style: 'decimal',
            minimumIntegerDigits: 3,
            useGrouping: false
            });


            This will produce the value of "005" for text. You can also use the toLocaleString function of Number to pad zeros to the right side of the decimal point.



            var amount = 5;

            var text = amount.toLocaleString('en-US',
            {
            style: 'decimal',
            minimumFractionDigits: 2,
            useGrouping: false
            });


            This will produce the value of "5.00" for text. Change useGrouping to true to use comma separators for thousands.



            Note that using toLocaleString() with locales and options arguments is standardized separately in ECMA-402, not in ECMAScript. As of today, some browsers only implement basic support, i.e. toLocaleString() may ignore any arguments.



            Complete Example







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 28 '15 at 21:01


























            community wiki





            2 revs, 2 users 95%
            Daniel Barbalace













            • Wow, this is a super clean solution and works in node.js.
              – jishi
              Feb 6 '16 at 22:21










            • I chuckled when I read the intro -- "needless complicated suggestions". Software development, as in all engineering disciplines, involves weighing trade-offs. I tried this "standard way" myself -- and timed it. It definitely works, but I would never choose to use it for any kind of repetitive application due to how slow it is compared to many of the other "home rolled" solutions.
              – bearvarine
              Sep 16 '17 at 20:47












            • True, a lot of built-in JavaScript functions perform poorly when looping over lots of data, but I would argue you should not use JavaScript for that, even server-side like Node.js. If you have lots of data to process server-side, you should use a better platform like .NET or Java. If you are processing client-side data for display to the end user, you should only process the data for what you are currently rendering to the end user's screen. For example, render only the visible rows of a table and don't process data for other roads.
              – Daniel Barbalace
              Jul 23 at 21:03




















            • Wow, this is a super clean solution and works in node.js.
              – jishi
              Feb 6 '16 at 22:21










            • I chuckled when I read the intro -- "needless complicated suggestions". Software development, as in all engineering disciplines, involves weighing trade-offs. I tried this "standard way" myself -- and timed it. It definitely works, but I would never choose to use it for any kind of repetitive application due to how slow it is compared to many of the other "home rolled" solutions.
              – bearvarine
              Sep 16 '17 at 20:47












            • True, a lot of built-in JavaScript functions perform poorly when looping over lots of data, but I would argue you should not use JavaScript for that, even server-side like Node.js. If you have lots of data to process server-side, you should use a better platform like .NET or Java. If you are processing client-side data for display to the end user, you should only process the data for what you are currently rendering to the end user's screen. For example, render only the visible rows of a table and don't process data for other roads.
              – Daniel Barbalace
              Jul 23 at 21:03


















            Wow, this is a super clean solution and works in node.js.
            – jishi
            Feb 6 '16 at 22:21




            Wow, this is a super clean solution and works in node.js.
            – jishi
            Feb 6 '16 at 22:21












            I chuckled when I read the intro -- "needless complicated suggestions". Software development, as in all engineering disciplines, involves weighing trade-offs. I tried this "standard way" myself -- and timed it. It definitely works, but I would never choose to use it for any kind of repetitive application due to how slow it is compared to many of the other "home rolled" solutions.
            – bearvarine
            Sep 16 '17 at 20:47






            I chuckled when I read the intro -- "needless complicated suggestions". Software development, as in all engineering disciplines, involves weighing trade-offs. I tried this "standard way" myself -- and timed it. It definitely works, but I would never choose to use it for any kind of repetitive application due to how slow it is compared to many of the other "home rolled" solutions.
            – bearvarine
            Sep 16 '17 at 20:47














            True, a lot of built-in JavaScript functions perform poorly when looping over lots of data, but I would argue you should not use JavaScript for that, even server-side like Node.js. If you have lots of data to process server-side, you should use a better platform like .NET or Java. If you are processing client-side data for display to the end user, you should only process the data for what you are currently rendering to the end user's screen. For example, render only the visible rows of a table and don't process data for other roads.
            – Daniel Barbalace
            Jul 23 at 21:03






            True, a lot of built-in JavaScript functions perform poorly when looping over lots of data, but I would argue you should not use JavaScript for that, even server-side like Node.js. If you have lots of data to process server-side, you should use a better platform like .NET or Java. If you are processing client-side data for display to the end user, you should only process the data for what you are currently rendering to the end user's screen. For example, render only the visible rows of a table and don't process data for other roads.
            – Daniel Barbalace
            Jul 23 at 21:03












            up vote
            20
            down vote













            If the fill number is known in advance not to exceed a certain value, there's another way to do this with no loops:



            var fillZeroes = "00000000000000000000";  // max number of zero fill ever asked for in global

            function zeroFill(number, width) {
            // make sure it's a string
            var input = number + "";
            var prefix = "";
            if (input.charAt(0) === '-') {
            prefix = "-";
            input = input.slice(1);
            --width;
            }
            var fillAmt = Math.max(width - input.length, 0);
            return prefix + fillZeroes.slice(0, fillAmt) + input;
            }


            Test cases here: http://jsfiddle.net/jfriend00/N87mZ/






            share|improve this answer























            • @BrockAdams - fixed for both cases you mention. If the number is already as wide as the fill width, then no fill is added.
              – jfriend00
              Jun 16 '13 at 1:08












            • Thanks; +1. The negative numbers are slightly off from the usual convention, though. In your test case, -88 should yield "-00088", for example.
              – Brock Adams
              Jun 16 '13 at 1:57








            • 1




              @BrockAdams - I wasn't sure whether calling zeroFill(-88, 5) should produce -00088 or -0088? I guess it depends upon whether you want the width argument to be the entire width of the number or just the number of digits (not including the negative sign). An implementer can easily switch the behavior to not include the negative sign by just removing the --width line of code.
              – jfriend00
              Jun 16 '13 at 3:07

















            up vote
            20
            down vote













            If the fill number is known in advance not to exceed a certain value, there's another way to do this with no loops:



            var fillZeroes = "00000000000000000000";  // max number of zero fill ever asked for in global

            function zeroFill(number, width) {
            // make sure it's a string
            var input = number + "";
            var prefix = "";
            if (input.charAt(0) === '-') {
            prefix = "-";
            input = input.slice(1);
            --width;
            }
            var fillAmt = Math.max(width - input.length, 0);
            return prefix + fillZeroes.slice(0, fillAmt) + input;
            }


            Test cases here: http://jsfiddle.net/jfriend00/N87mZ/






            share|improve this answer























            • @BrockAdams - fixed for both cases you mention. If the number is already as wide as the fill width, then no fill is added.
              – jfriend00
              Jun 16 '13 at 1:08












            • Thanks; +1. The negative numbers are slightly off from the usual convention, though. In your test case, -88 should yield "-00088", for example.
              – Brock Adams
              Jun 16 '13 at 1:57








            • 1




              @BrockAdams - I wasn't sure whether calling zeroFill(-88, 5) should produce -00088 or -0088? I guess it depends upon whether you want the width argument to be the entire width of the number or just the number of digits (not including the negative sign). An implementer can easily switch the behavior to not include the negative sign by just removing the --width line of code.
              – jfriend00
              Jun 16 '13 at 3:07















            up vote
            20
            down vote










            up vote
            20
            down vote









            If the fill number is known in advance not to exceed a certain value, there's another way to do this with no loops:



            var fillZeroes = "00000000000000000000";  // max number of zero fill ever asked for in global

            function zeroFill(number, width) {
            // make sure it's a string
            var input = number + "";
            var prefix = "";
            if (input.charAt(0) === '-') {
            prefix = "-";
            input = input.slice(1);
            --width;
            }
            var fillAmt = Math.max(width - input.length, 0);
            return prefix + fillZeroes.slice(0, fillAmt) + input;
            }


            Test cases here: http://jsfiddle.net/jfriend00/N87mZ/






            share|improve this answer














            If the fill number is known in advance not to exceed a certain value, there's another way to do this with no loops:



            var fillZeroes = "00000000000000000000";  // max number of zero fill ever asked for in global

            function zeroFill(number, width) {
            // make sure it's a string
            var input = number + "";
            var prefix = "";
            if (input.charAt(0) === '-') {
            prefix = "-";
            input = input.slice(1);
            --width;
            }
            var fillAmt = Math.max(width - input.length, 0);
            return prefix + fillZeroes.slice(0, fillAmt) + input;
            }


            Test cases here: http://jsfiddle.net/jfriend00/N87mZ/







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jun 16 '13 at 1:08


























            community wiki





            jfriend00













            • @BrockAdams - fixed for both cases you mention. If the number is already as wide as the fill width, then no fill is added.
              – jfriend00
              Jun 16 '13 at 1:08












            • Thanks; +1. The negative numbers are slightly off from the usual convention, though. In your test case, -88 should yield "-00088", for example.
              – Brock Adams
              Jun 16 '13 at 1:57








            • 1




              @BrockAdams - I wasn't sure whether calling zeroFill(-88, 5) should produce -00088 or -0088? I guess it depends upon whether you want the width argument to be the entire width of the number or just the number of digits (not including the negative sign). An implementer can easily switch the behavior to not include the negative sign by just removing the --width line of code.
              – jfriend00
              Jun 16 '13 at 3:07




















            • @BrockAdams - fixed for both cases you mention. If the number is already as wide as the fill width, then no fill is added.
              – jfriend00
              Jun 16 '13 at 1:08












            • Thanks; +1. The negative numbers are slightly off from the usual convention, though. In your test case, -88 should yield "-00088", for example.
              – Brock Adams
              Jun 16 '13 at 1:57








            • 1




              @BrockAdams - I wasn't sure whether calling zeroFill(-88, 5) should produce -00088 or -0088? I guess it depends upon whether you want the width argument to be the entire width of the number or just the number of digits (not including the negative sign). An implementer can easily switch the behavior to not include the negative sign by just removing the --width line of code.
              – jfriend00
              Jun 16 '13 at 3:07


















            @BrockAdams - fixed for both cases you mention. If the number is already as wide as the fill width, then no fill is added.
            – jfriend00
            Jun 16 '13 at 1:08






            @BrockAdams - fixed for both cases you mention. If the number is already as wide as the fill width, then no fill is added.
            – jfriend00
            Jun 16 '13 at 1:08














            Thanks; +1. The negative numbers are slightly off from the usual convention, though. In your test case, -88 should yield "-00088", for example.
            – Brock Adams
            Jun 16 '13 at 1:57






            Thanks; +1. The negative numbers are slightly off from the usual convention, though. In your test case, -88 should yield "-00088", for example.
            – Brock Adams
            Jun 16 '13 at 1:57






            1




            1




            @BrockAdams - I wasn't sure whether calling zeroFill(-88, 5) should produce -00088 or -0088? I guess it depends upon whether you want the width argument to be the entire width of the number or just the number of digits (not including the negative sign). An implementer can easily switch the behavior to not include the negative sign by just removing the --width line of code.
            – jfriend00
            Jun 16 '13 at 3:07






            @BrockAdams - I wasn't sure whether calling zeroFill(-88, 5) should produce -00088 or -0088? I guess it depends upon whether you want the width argument to be the entire width of the number or just the number of digits (not including the negative sign). An implementer can easily switch the behavior to not include the negative sign by just removing the --width line of code.
            – jfriend00
            Jun 16 '13 at 3:07












            up vote
            18
            down vote













            In a proposed (stage 3) ES2017 method .padStart() you can simply now do (when implemented/supported):



            string.padStart(maxLength, "0"); //max length is the max string length, not max # of fills





            share|improve this answer























            • I've been looking for this one for some time now. Thank you for giving some visibility. I hope in 2030 we have it working.
              – dinigo
              Jun 20 '17 at 10:55






            • 1




              Its works now @dinigo ^^ it is live
              – Paulo Roberto
              Nov 22 '17 at 12:47










            • yep, I've used it a couple of times
              – dinigo
              Nov 22 '17 at 13:02















            up vote
            18
            down vote













            In a proposed (stage 3) ES2017 method .padStart() you can simply now do (when implemented/supported):



            string.padStart(maxLength, "0"); //max length is the max string length, not max # of fills





            share|improve this answer























            • I've been looking for this one for some time now. Thank you for giving some visibility. I hope in 2030 we have it working.
              – dinigo
              Jun 20 '17 at 10:55






            • 1




              Its works now @dinigo ^^ it is live
              – Paulo Roberto
              Nov 22 '17 at 12:47










            • yep, I've used it a couple of times
              – dinigo
              Nov 22 '17 at 13:02













            up vote
            18
            down vote










            up vote
            18
            down vote









            In a proposed (stage 3) ES2017 method .padStart() you can simply now do (when implemented/supported):



            string.padStart(maxLength, "0"); //max length is the max string length, not max # of fills





            share|improve this answer














            In a proposed (stage 3) ES2017 method .padStart() you can simply now do (when implemented/supported):



            string.padStart(maxLength, "0"); //max length is the max string length, not max # of fills






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 16 '16 at 14:25


























            community wiki





            2 revs
            Sterling Archer













            • I've been looking for this one for some time now. Thank you for giving some visibility. I hope in 2030 we have it working.
              – dinigo
              Jun 20 '17 at 10:55






            • 1




              Its works now @dinigo ^^ it is live
              – Paulo Roberto
              Nov 22 '17 at 12:47










            • yep, I've used it a couple of times
              – dinigo
              Nov 22 '17 at 13:02


















            • I've been looking for this one for some time now. Thank you for giving some visibility. I hope in 2030 we have it working.
              – dinigo
              Jun 20 '17 at 10:55






            • 1




              Its works now @dinigo ^^ it is live
              – Paulo Roberto
              Nov 22 '17 at 12:47










            • yep, I've used it a couple of times
              – dinigo
              Nov 22 '17 at 13:02
















            I've been looking for this one for some time now. Thank you for giving some visibility. I hope in 2030 we have it working.
            – dinigo
            Jun 20 '17 at 10:55




            I've been looking for this one for some time now. Thank you for giving some visibility. I hope in 2030 we have it working.
            – dinigo
            Jun 20 '17 at 10:55




            1




            1




            Its works now @dinigo ^^ it is live
            – Paulo Roberto
            Nov 22 '17 at 12:47




            Its works now @dinigo ^^ it is live
            – Paulo Roberto
            Nov 22 '17 at 12:47












            yep, I've used it a couple of times
            – dinigo
            Nov 22 '17 at 13:02




            yep, I've used it a couple of times
            – dinigo
            Nov 22 '17 at 13:02










            up vote
            17
            down vote













            The quick and dirty way:



            y = (new Array(count + 1 - x.toString().length)).join('0') + x;


            For x = 5 and count = 6 you'll have y = "000005"






            share|improve this answer



















            • 1




              I got y="0005" with the above, y = (new Array(count + 1 - x.toString().length)).join('0') + x; is what gave me y="000005"
              – forforf
              May 23 '12 at 15:30










            • @forforf thanks, corrected it now!
              – Johann Philipp Strathausen
              May 24 '12 at 22:48










            • Thanks. I always like the shortest code solution.
              – Orr Siloni
              Nov 12 '12 at 14:08






            • 3




              @OrrSiloni: the shortest code solution is actually ('0000'+n).slice(-4)
              – Seaux
              Dec 8 '13 at 23:17

















            up vote
            17
            down vote













            The quick and dirty way:



            y = (new Array(count + 1 - x.toString().length)).join('0') + x;


            For x = 5 and count = 6 you'll have y = "000005"






            share|improve this answer



















            • 1




              I got y="0005" with the above, y = (new Array(count + 1 - x.toString().length)).join('0') + x; is what gave me y="000005"
              – forforf
              May 23 '12 at 15:30










            • @forforf thanks, corrected it now!
              – Johann Philipp Strathausen
              May 24 '12 at 22:48










            • Thanks. I always like the shortest code solution.
              – Orr Siloni
              Nov 12 '12 at 14:08






            • 3




              @OrrSiloni: the shortest code solution is actually ('0000'+n).slice(-4)
              – Seaux
              Dec 8 '13 at 23:17















            up vote
            17
            down vote










            up vote
            17
            down vote









            The quick and dirty way:



            y = (new Array(count + 1 - x.toString().length)).join('0') + x;


            For x = 5 and count = 6 you'll have y = "000005"






            share|improve this answer














            The quick and dirty way:



            y = (new Array(count + 1 - x.toString().length)).join('0') + x;


            For x = 5 and count = 6 you'll have y = "000005"







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited May 24 '12 at 22:47


























            community wiki





            Johann Philipp Strathausen









            • 1




              I got y="0005" with the above, y = (new Array(count + 1 - x.toString().length)).join('0') + x; is what gave me y="000005"
              – forforf
              May 23 '12 at 15:30










            • @forforf thanks, corrected it now!
              – Johann Philipp Strathausen
              May 24 '12 at 22:48










            • Thanks. I always like the shortest code solution.
              – Orr Siloni
              Nov 12 '12 at 14:08






            • 3




              @OrrSiloni: the shortest code solution is actually ('0000'+n).slice(-4)
              – Seaux
              Dec 8 '13 at 23:17
















            • 1




              I got y="0005" with the above, y = (new Array(count + 1 - x.toString().length)).join('0') + x; is what gave me y="000005"
              – forforf
              May 23 '12 at 15:30










            • @forforf thanks, corrected it now!
              – Johann Philipp Strathausen
              May 24 '12 at 22:48










            • Thanks. I always like the shortest code solution.
              – Orr Siloni
              Nov 12 '12 at 14:08






            • 3




              @OrrSiloni: the shortest code solution is actually ('0000'+n).slice(-4)
              – Seaux
              Dec 8 '13 at 23:17










            1




            1




            I got y="0005" with the above, y = (new Array(count + 1 - x.toString().length)).join('0') + x; is what gave me y="000005"
            – forforf
            May 23 '12 at 15:30




            I got y="0005" with the above, y = (new Array(count + 1 - x.toString().length)).join('0') + x; is what gave me y="000005"
            – forforf
            May 23 '12 at 15:30












            @forforf thanks, corrected it now!
            – Johann Philipp Strathausen
            May 24 '12 at 22:48




            @forforf thanks, corrected it now!
            – Johann Philipp Strathausen
            May 24 '12 at 22:48












            Thanks. I always like the shortest code solution.
            – Orr Siloni
            Nov 12 '12 at 14:08




            Thanks. I always like the shortest code solution.
            – Orr Siloni
            Nov 12 '12 at 14:08




            3




            3




            @OrrSiloni: the shortest code solution is actually ('0000'+n).slice(-4)
            – Seaux
            Dec 8 '13 at 23:17






            @OrrSiloni: the shortest code solution is actually ('0000'+n).slice(-4)
            – Seaux
            Dec 8 '13 at 23:17












            up vote
            12
            down vote













            Here's a quick function I came up with to do the job. If anyone has a simpler approach, feel free to share!



            function zerofill(number, length) {
            // Setup
            var result = number.toString();
            var pad = length - result.length;

            while(pad > 0) {
            result = '0' + result;
            pad--;
            }

            return result;
            }





            share|improve this answer























            • I don't think there will be a "simpler" solution - it will always be a function of some sort. We could have a algorithm discussion, but at the end of the day, you'll still end up with a function that zerofills a number.
              – Peter Bailey
              Aug 12 '09 at 17:54










            • My general advice is to use "for" loops as they are generally more stable and faster in ECMAScript languages (ActionScript 1-3, and JavaScript)
              – cwallenpoole
              Aug 12 '09 at 18:03










            • Or, skip iteration altogether ;)
              – Peter Bailey
              Aug 12 '09 at 20:05










            • Simpler function? Probably not. One that doesn't loop? That is possible... though the algorithm isn't entirely trivial.
              – coderjoe
              Aug 12 '09 at 20:09






            • 1




              Wow, pretty much all the above comments are incorrect. @profitehlolz's solution is simpler and suitable for inlining (doesn't need to be a function). Meanwhile, for .vs. while performance is not different enough to be interesting: jsperf.com/fors-vs-while/34
              – broofa
              Sep 24 '12 at 12:07

















            up vote
            12
            down vote













            Here's a quick function I came up with to do the job. If anyone has a simpler approach, feel free to share!



            function zerofill(number, length) {
            // Setup
            var result = number.toString();
            var pad = length - result.length;

            while(pad > 0) {
            result = '0' + result;
            pad--;
            }

            return result;
            }





            share|improve this answer























            • I don't think there will be a "simpler" solution - it will always be a function of some sort. We could have a algorithm discussion, but at the end of the day, you'll still end up with a function that zerofills a number.
              – Peter Bailey
              Aug 12 '09 at 17:54










            • My general advice is to use "for" loops as they are generally more stable and faster in ECMAScript languages (ActionScript 1-3, and JavaScript)
              – cwallenpoole
              Aug 12 '09 at 18:03










            • Or, skip iteration altogether ;)
              – Peter Bailey
              Aug 12 '09 at 20:05










            • Simpler function? Probably not. One that doesn't loop? That is possible... though the algorithm isn't entirely trivial.
              – coderjoe
              Aug 12 '09 at 20:09






            • 1




              Wow, pretty much all the above comments are incorrect. @profitehlolz's solution is simpler and suitable for inlining (doesn't need to be a function). Meanwhile, for .vs. while performance is not different enough to be interesting: jsperf.com/fors-vs-while/34
              – broofa
              Sep 24 '12 at 12:07















            up vote
            12
            down vote










            up vote
            12
            down vote









            Here's a quick function I came up with to do the job. If anyone has a simpler approach, feel free to share!



            function zerofill(number, length) {
            // Setup
            var result = number.toString();
            var pad = length - result.length;

            while(pad > 0) {
            result = '0' + result;
            pad--;
            }

            return result;
            }





            share|improve this answer














            Here's a quick function I came up with to do the job. If anyone has a simpler approach, feel free to share!



            function zerofill(number, length) {
            // Setup
            var result = number.toString();
            var pad = length - result.length;

            while(pad > 0) {
            result = '0' + result;
            pad--;
            }

            return result;
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            answered Aug 12 '09 at 16:54


























            community wiki





            Wilco













            • I don't think there will be a "simpler" solution - it will always be a function of some sort. We could have a algorithm discussion, but at the end of the day, you'll still end up with a function that zerofills a number.
              – Peter Bailey
              Aug 12 '09 at 17:54










            • My general advice is to use "for" loops as they are generally more stable and faster in ECMAScript languages (ActionScript 1-3, and JavaScript)
              – cwallenpoole
              Aug 12 '09 at 18:03










            • Or, skip iteration altogether ;)
              – Peter Bailey
              Aug 12 '09 at 20:05










            • Simpler function? Probably not. One that doesn't loop? That is possible... though the algorithm isn't entirely trivial.
              – coderjoe
              Aug 12 '09 at 20:09






            • 1




              Wow, pretty much all the above comments are incorrect. @profitehlolz's solution is simpler and suitable for inlining (doesn't need to be a function). Meanwhile, for .vs. while performance is not different enough to be interesting: jsperf.com/fors-vs-while/34
              – broofa
              Sep 24 '12 at 12:07




















            • I don't think there will be a "simpler" solution - it will always be a function of some sort. We could have a algorithm discussion, but at the end of the day, you'll still end up with a function that zerofills a number.
              – Peter Bailey
              Aug 12 '09 at 17:54










            • My general advice is to use "for" loops as they are generally more stable and faster in ECMAScript languages (ActionScript 1-3, and JavaScript)
              – cwallenpoole
              Aug 12 '09 at 18:03










            • Or, skip iteration altogether ;)
              – Peter Bailey
              Aug 12 '09 at 20:05










            • Simpler function? Probably not. One that doesn't loop? That is possible... though the algorithm isn't entirely trivial.
              – coderjoe
              Aug 12 '09 at 20:09






            • 1




              Wow, pretty much all the above comments are incorrect. @profitehlolz's solution is simpler and suitable for inlining (doesn't need to be a function). Meanwhile, for .vs. while performance is not different enough to be interesting: jsperf.com/fors-vs-while/34
              – broofa
              Sep 24 '12 at 12:07


















            I don't think there will be a "simpler" solution - it will always be a function of some sort. We could have a algorithm discussion, but at the end of the day, you'll still end up with a function that zerofills a number.
            – Peter Bailey
            Aug 12 '09 at 17:54




            I don't think there will be a "simpler" solution - it will always be a function of some sort. We could have a algorithm discussion, but at the end of the day, you'll still end up with a function that zerofills a number.
            – Peter Bailey
            Aug 12 '09 at 17:54












            My general advice is to use "for" loops as they are generally more stable and faster in ECMAScript languages (ActionScript 1-3, and JavaScript)
            – cwallenpoole
            Aug 12 '09 at 18:03




            My general advice is to use "for" loops as they are generally more stable and faster in ECMAScript languages (ActionScript 1-3, and JavaScript)
            – cwallenpoole
            Aug 12 '09 at 18:03












            Or, skip iteration altogether ;)
            – Peter Bailey
            Aug 12 '09 at 20:05




            Or, skip iteration altogether ;)
            – Peter Bailey
            Aug 12 '09 at 20:05












            Simpler function? Probably not. One that doesn't loop? That is possible... though the algorithm isn't entirely trivial.
            – coderjoe
            Aug 12 '09 at 20:09




            Simpler function? Probably not. One that doesn't loop? That is possible... though the algorithm isn't entirely trivial.
            – coderjoe
            Aug 12 '09 at 20:09




            1




            1




            Wow, pretty much all the above comments are incorrect. @profitehlolz's solution is simpler and suitable for inlining (doesn't need to be a function). Meanwhile, for .vs. while performance is not different enough to be interesting: jsperf.com/fors-vs-while/34
            – broofa
            Sep 24 '12 at 12:07






            Wow, pretty much all the above comments are incorrect. @profitehlolz's solution is simpler and suitable for inlining (doesn't need to be a function). Meanwhile, for .vs. while performance is not different enough to be interesting: jsperf.com/fors-vs-while/34
            – broofa
            Sep 24 '12 at 12:07












            up vote
            11
            down vote













            Late to the party here, but I often use this construct for doing ad-hoc padding of some value n, known to be a positive, decimal:



            (offset + n + '').substr(1);


            Where offset is 10^^digits.



            E.g. Padding to 5 digits, where n = 123:



            (1e5 + 123 + '').substr(1); // => 00123


            The hexidecimal version of this is slightly more verbose:



            (0x100000 + 0x123).toString(16).substr(1); // => 00123


            Note 1: I like @profitehlolz's solution as well, which is the string version of this, using slice()'s nifty negative-index feature.






            share|improve this answer























            • Very elegant and neat!
              – Marc
              Feb 13 '13 at 9:42















            up vote
            11
            down vote













            Late to the party here, but I often use this construct for doing ad-hoc padding of some value n, known to be a positive, decimal:



            (offset + n + '').substr(1);


            Where offset is 10^^digits.



            E.g. Padding to 5 digits, where n = 123:



            (1e5 + 123 + '').substr(1); // => 00123


            The hexidecimal version of this is slightly more verbose:



            (0x100000 + 0x123).toString(16).substr(1); // => 00123


            Note 1: I like @profitehlolz's solution as well, which is the string version of this, using slice()'s nifty negative-index feature.






            share|improve this answer























            • Very elegant and neat!
              – Marc
              Feb 13 '13 at 9:42













            up vote
            11
            down vote










            up vote
            11
            down vote









            Late to the party here, but I often use this construct for doing ad-hoc padding of some value n, known to be a positive, decimal:



            (offset + n + '').substr(1);


            Where offset is 10^^digits.



            E.g. Padding to 5 digits, where n = 123:



            (1e5 + 123 + '').substr(1); // => 00123


            The hexidecimal version of this is slightly more verbose:



            (0x100000 + 0x123).toString(16).substr(1); // => 00123


            Note 1: I like @profitehlolz's solution as well, which is the string version of this, using slice()'s nifty negative-index feature.






            share|improve this answer














            Late to the party here, but I often use this construct for doing ad-hoc padding of some value n, known to be a positive, decimal:



            (offset + n + '').substr(1);


            Where offset is 10^^digits.



            E.g. Padding to 5 digits, where n = 123:



            (1e5 + 123 + '').substr(1); // => 00123


            The hexidecimal version of this is slightly more verbose:



            (0x100000 + 0x123).toString(16).substr(1); // => 00123


            Note 1: I like @profitehlolz's solution as well, which is the string version of this, using slice()'s nifty negative-index feature.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            answered Sep 24 '12 at 12:25


























            community wiki





            broofa













            • Very elegant and neat!
              – Marc
              Feb 13 '13 at 9:42


















            • Very elegant and neat!
              – Marc
              Feb 13 '13 at 9:42
















            Very elegant and neat!
            – Marc
            Feb 13 '13 at 9:42




            Very elegant and neat!
            – Marc
            Feb 13 '13 at 9:42










            up vote
            11
            down vote













            I really don't know why, but no one did it in the most obvious way. Here it's my implementation.



            Function:



            /** Pad a number with 0 on the left */
            function zeroPad(number, digits) {
            var num = number+"";
            while(num.length < digits){
            num='0'+num;
            }
            return num;
            }


            Prototype:



            Number.prototype.zeroPad=function(digits){
            var num=this+"";
            while(num.length < digits){
            num='0'+num;
            }
            return(num);
            };


            Very straightforward, I can't see any way how this can be any simpler. For some reason I've seem many times here on SO, people just try to avoid 'for' and 'while' loops at any cost. Using regex will probably cost way more cycles for such a trivial 8 digit padding.






            share|improve this answer



























              up vote
              11
              down vote













              I really don't know why, but no one did it in the most obvious way. Here it's my implementation.



              Function:



              /** Pad a number with 0 on the left */
              function zeroPad(number, digits) {
              var num = number+"";
              while(num.length < digits){
              num='0'+num;
              }
              return num;
              }


              Prototype:



              Number.prototype.zeroPad=function(digits){
              var num=this+"";
              while(num.length < digits){
              num='0'+num;
              }
              return(num);
              };


              Very straightforward, I can't see any way how this can be any simpler. For some reason I've seem many times here on SO, people just try to avoid 'for' and 'while' loops at any cost. Using regex will probably cost way more cycles for such a trivial 8 digit padding.






              share|improve this answer

























                up vote
                11
                down vote










                up vote
                11
                down vote









                I really don't know why, but no one did it in the most obvious way. Here it's my implementation.



                Function:



                /** Pad a number with 0 on the left */
                function zeroPad(number, digits) {
                var num = number+"";
                while(num.length < digits){
                num='0'+num;
                }
                return num;
                }


                Prototype:



                Number.prototype.zeroPad=function(digits){
                var num=this+"";
                while(num.length < digits){
                num='0'+num;
                }
                return(num);
                };


                Very straightforward, I can't see any way how this can be any simpler. For some reason I've seem many times here on SO, people just try to avoid 'for' and 'while' loops at any cost. Using regex will probably cost way more cycles for such a trivial 8 digit padding.






                share|improve this answer














                I really don't know why, but no one did it in the most obvious way. Here it's my implementation.



                Function:



                /** Pad a number with 0 on the left */
                function zeroPad(number, digits) {
                var num = number+"";
                while(num.length < digits){
                num='0'+num;
                }
                return num;
                }


                Prototype:



                Number.prototype.zeroPad=function(digits){
                var num=this+"";
                while(num.length < digits){
                num='0'+num;
                }
                return(num);
                };


                Very straightforward, I can't see any way how this can be any simpler. For some reason I've seem many times here on SO, people just try to avoid 'for' and 'while' loops at any cost. Using regex will probably cost way more cycles for such a trivial 8 digit padding.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                answered Feb 5 '13 at 14:45


























                community wiki





                Vitim.us























                    up vote
                    9
                    down vote













                    I use this snipet to get a 5 digits representation



                    (value+100000).toString().slice(-5) // "00123" with value=123





                    share|improve this answer























                    • this is a smart way to add leading zero . I have done something similar to add leading zero for fixed length binary integer
                      – Chris.Huang
                      May 11 '15 at 2:14















                    up vote
                    9
                    down vote













                    I use this snipet to get a 5 digits representation



                    (value+100000).toString().slice(-5) // "00123" with value=123





                    share|improve this answer























                    • this is a smart way to add leading zero . I have done something similar to add leading zero for fixed length binary integer
                      – Chris.Huang
                      May 11 '15 at 2:14













                    up vote
                    9
                    down vote










                    up vote
                    9
                    down vote









                    I use this snipet to get a 5 digits representation



                    (value+100000).toString().slice(-5) // "00123" with value=123





                    share|improve this answer














                    I use this snipet to get a 5 digits representation



                    (value+100000).toString().slice(-5) // "00123" with value=123






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    answered Sep 3 '13 at 11:08


























                    community wiki





                    jasto salto













                    • this is a smart way to add leading zero . I have done something similar to add leading zero for fixed length binary integer
                      – Chris.Huang
                      May 11 '15 at 2:14


















                    • this is a smart way to add leading zero . I have done something similar to add leading zero for fixed length binary integer
                      – Chris.Huang
                      May 11 '15 at 2:14
















                    this is a smart way to add leading zero . I have done something similar to add leading zero for fixed length binary integer
                    – Chris.Huang
                    May 11 '15 at 2:14




                    this is a smart way to add leading zero . I have done something similar to add leading zero for fixed length binary integer
                    – Chris.Huang
                    May 11 '15 at 2:14










                    up vote
                    8
                    down vote













                    The power of Math!



                    x = integer to pad

                    y = number of zeroes to pad



                    function zeroPad(x, y)
                    {
                    y = Math.max(y-1,0);
                    var n = (x / Math.pow(10,y)).toFixed(y);
                    return n.replace('.','');
                    }





                    share|improve this answer























                    • Wow, that is a very clever way to solve this problem. I already had my own solution for this that is exactly functionally equivalent, and even relatively short, but this is concise and probably quite fast.
                      – pseudosavant
                      Jan 9 '14 at 21:10















                    up vote
                    8
                    down vote













                    The power of Math!



                    x = integer to pad

                    y = number of zeroes to pad



                    function zeroPad(x, y)
                    {
                    y = Math.max(y-1,0);
                    var n = (x / Math.pow(10,y)).toFixed(y);
                    return n.replace('.','');
                    }





                    share|improve this answer























                    • Wow, that is a very clever way to solve this problem. I already had my own solution for this that is exactly functionally equivalent, and even relatively short, but this is concise and probably quite fast.
                      – pseudosavant
                      Jan 9 '14 at 21:10













                    up vote
                    8
                    down vote










                    up vote
                    8
                    down vote









                    The power of Math!



                    x = integer to pad

                    y = number of zeroes to pad



                    function zeroPad(x, y)
                    {
                    y = Math.max(y-1,0);
                    var n = (x / Math.pow(10,y)).toFixed(y);
                    return n.replace('.','');
                    }





                    share|improve this answer














                    The power of Math!



                    x = integer to pad

                    y = number of zeroes to pad



                    function zeroPad(x, y)
                    {
                    y = Math.max(y-1,0);
                    var n = (x / Math.pow(10,y)).toFixed(y);
                    return n.replace('.','');
                    }






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    answered Mar 21 '13 at 1:40


























                    community wiki





                    tir













                    • Wow, that is a very clever way to solve this problem. I already had my own solution for this that is exactly functionally equivalent, and even relatively short, but this is concise and probably quite fast.
                      – pseudosavant
                      Jan 9 '14 at 21:10


















                    • Wow, that is a very clever way to solve this problem. I already had my own solution for this that is exactly functionally equivalent, and even relatively short, but this is concise and probably quite fast.
                      – pseudosavant
                      Jan 9 '14 at 21:10
















                    Wow, that is a very clever way to solve this problem. I already had my own solution for this that is exactly functionally equivalent, and even relatively short, but this is concise and probably quite fast.
                    – pseudosavant
                    Jan 9 '14 at 21:10




                    Wow, that is a very clever way to solve this problem. I already had my own solution for this that is exactly functionally equivalent, and even relatively short, but this is concise and probably quite fast.
                    – pseudosavant
                    Jan 9 '14 at 21:10










                    up vote
                    7
                    down vote













                    First parameter is any real number, second parameter is a positive integer specifying the minimum number of digits to the left of the decimal point and third parameter is an optional positive integer specifying the number if digits to the right of the decimal point.



                    function zPad(n, l, r){
                    return(a=String(n).match(/(^-?)(d*).?(d*)/))?a[1]+(Array(l).join(0)+a[2]).slice(-Math.max(l,a[2].length))+('undefined'!==typeof r?(0<r?'.':'')+(a[3]+Array(r+1).join(0)).slice(0,r):a[3]?'.'+a[3]:''):0
                    }


                    so



                               zPad(6, 2) === '06'
                    zPad(-6, 2) === '-06'
                    zPad(600.2, 2) === '600.2'
                    zPad(-600, 2) === '-600'
                    zPad(6.2, 3) === '006.2'
                    zPad(-6.2, 3) === '-006.2'
                    zPad(6.2, 3, 0) === '006'
                    zPad(6, 2, 3) === '06.000'
                    zPad(600.2, 2, 3) === '600.200'
                    zPad(-600.1499, 2, 3) === '-600.149'





                    share|improve this answer



























                      up vote
                      7
                      down vote













                      First parameter is any real number, second parameter is a positive integer specifying the minimum number of digits to the left of the decimal point and third parameter is an optional positive integer specifying the number if digits to the right of the decimal point.



                      function zPad(n, l, r){
                      return(a=String(n).match(/(^-?)(d*).?(d*)/))?a[1]+(Array(l).join(0)+a[2]).slice(-Math.max(l,a[2].length))+('undefined'!==typeof r?(0<r?'.':'')+(a[3]+Array(r+1).join(0)).slice(0,r):a[3]?'.'+a[3]:''):0
                      }


                      so



                                 zPad(6, 2) === '06'
                      zPad(-6, 2) === '-06'
                      zPad(600.2, 2) === '600.2'
                      zPad(-600, 2) === '-600'
                      zPad(6.2, 3) === '006.2'
                      zPad(-6.2, 3) === '-006.2'
                      zPad(6.2, 3, 0) === '006'
                      zPad(6, 2, 3) === '06.000'
                      zPad(600.2, 2, 3) === '600.200'
                      zPad(-600.1499, 2, 3) === '-600.149'





                      share|improve this answer

























                        up vote
                        7
                        down vote










                        up vote
                        7
                        down vote









                        First parameter is any real number, second parameter is a positive integer specifying the minimum number of digits to the left of the decimal point and third parameter is an optional positive integer specifying the number if digits to the right of the decimal point.



                        function zPad(n, l, r){
                        return(a=String(n).match(/(^-?)(d*).?(d*)/))?a[1]+(Array(l).join(0)+a[2]).slice(-Math.max(l,a[2].length))+('undefined'!==typeof r?(0<r?'.':'')+(a[3]+Array(r+1).join(0)).slice(0,r):a[3]?'.'+a[3]:''):0
                        }


                        so



                                   zPad(6, 2) === '06'
                        zPad(-6, 2) === '-06'
                        zPad(600.2, 2) === '600.2'
                        zPad(-600, 2) === '-600'
                        zPad(6.2, 3) === '006.2'
                        zPad(-6.2, 3) === '-006.2'
                        zPad(6.2, 3, 0) === '006'
                        zPad(6, 2, 3) === '06.000'
                        zPad(600.2, 2, 3) === '600.200'
                        zPad(-600.1499, 2, 3) === '-600.149'





                        share|improve this answer














                        First parameter is any real number, second parameter is a positive integer specifying the minimum number of digits to the left of the decimal point and third parameter is an optional positive integer specifying the number if digits to the right of the decimal point.



                        function zPad(n, l, r){
                        return(a=String(n).match(/(^-?)(d*).?(d*)/))?a[1]+(Array(l).join(0)+a[2]).slice(-Math.max(l,a[2].length))+('undefined'!==typeof r?(0<r?'.':'')+(a[3]+Array(r+1).join(0)).slice(0,r):a[3]?'.'+a[3]:''):0
                        }


                        so



                                   zPad(6, 2) === '06'
                        zPad(-6, 2) === '-06'
                        zPad(600.2, 2) === '600.2'
                        zPad(-600, 2) === '-600'
                        zPad(6.2, 3) === '006.2'
                        zPad(-6.2, 3) === '-006.2'
                        zPad(6.2, 3, 0) === '006'
                        zPad(6, 2, 3) === '06.000'
                        zPad(600.2, 2, 3) === '600.200'
                        zPad(-600.1499, 2, 3) === '-600.149'






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Feb 4 '14 at 22:52


























                        community wiki





                        4 revs
                        Jack Allan























                            up vote
                            7
                            down vote













                            Don't reinvent the wheel, use underscore string:



                            jsFiddle



                            var numToPad = '5';

                            alert(_.str.pad(numToPad, 6, '0')); // yields: '000005'





                            share|improve this answer



















                            • 1




                              Pure JavaScript! Short and simple, and a jsFiddle example! EXCELLENT! :D
                              – tfont
                              Oct 10 '14 at 23:41















                            up vote
                            7
                            down vote













                            Don't reinvent the wheel, use underscore string:



                            jsFiddle



                            var numToPad = '5';

                            alert(_.str.pad(numToPad, 6, '0')); // yields: '000005'





                            share|improve this answer



















                            • 1




                              Pure JavaScript! Short and simple, and a jsFiddle example! EXCELLENT! :D
                              – tfont
                              Oct 10 '14 at 23:41













                            up vote
                            7
                            down vote










                            up vote
                            7
                            down vote









                            Don't reinvent the wheel, use underscore string:



                            jsFiddle



                            var numToPad = '5';

                            alert(_.str.pad(numToPad, 6, '0')); // yields: '000005'





                            share|improve this answer














                            Don't reinvent the wheel, use underscore string:



                            jsFiddle



                            var numToPad = '5';

                            alert(_.str.pad(numToPad, 6, '0')); // yields: '000005'






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            answered Sep 5 '14 at 12:34


























                            community wiki





                            Benny Bottema









                            • 1




                              Pure JavaScript! Short and simple, and a jsFiddle example! EXCELLENT! :D
                              – tfont
                              Oct 10 '14 at 23:41














                            • 1




                              Pure JavaScript! Short and simple, and a jsFiddle example! EXCELLENT! :D
                              – tfont
                              Oct 10 '14 at 23:41








                            1




                            1




                            Pure JavaScript! Short and simple, and a jsFiddle example! EXCELLENT! :D
                            – tfont
                            Oct 10 '14 at 23:41




                            Pure JavaScript! Short and simple, and a jsFiddle example! EXCELLENT! :D
                            – tfont
                            Oct 10 '14 at 23:41










                            up vote
                            7
                            down vote













                            This is the ES6 solution.






                            function pad(num, len) {
                            return '0'.repeat(len - num.toString().length) + num;
                            }
                            alert(pad(1234,6));








                            share|improve this answer























                            • Clearly the most elegant solution I would just modify it to avoid 2 string conversions: const numStr = String(num) and return '0'.repeat(len - numStr.length) + numStr;
                              – ngryman
                              Sep 26 '16 at 21:52

















                            up vote
                            7
                            down vote













                            This is the ES6 solution.






                            function pad(num, len) {
                            return '0'.repeat(len - num.toString().length) + num;
                            }
                            alert(pad(1234,6));








                            share|improve this answer























                            • Clearly the most elegant solution I would just modify it to avoid 2 string conversions: const numStr = String(num) and return '0'.repeat(len - numStr.length) + numStr;
                              – ngryman
                              Sep 26 '16 at 21:52















                            up vote
                            7
                            down vote










                            up vote
                            7
                            down vote









                            This is the ES6 solution.






                            function pad(num, len) {
                            return '0'.repeat(len - num.toString().length) + num;
                            }
                            alert(pad(1234,6));








                            share|improve this answer














                            This is the ES6 solution.






                            function pad(num, len) {
                            return '0'.repeat(len - num.toString().length) + num;
                            }
                            alert(pad(1234,6));








                            function pad(num, len) {
                            return '0'.repeat(len - num.toString().length) + num;
                            }
                            alert(pad(1234,6));





                            function pad(num, len) {
                            return '0'.repeat(len - num.toString().length) + num;
                            }
                            alert(pad(1234,6));






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            answered May 22 '15 at 3:38


























                            community wiki





                            Lewis













                            • Clearly the most elegant solution I would just modify it to avoid 2 string conversions: const numStr = String(num) and return '0'.repeat(len - numStr.length) + numStr;
                              – ngryman
                              Sep 26 '16 at 21:52




















                            • Clearly the most elegant solution I would just modify it to avoid 2 string conversions: const numStr = String(num) and return '0'.repeat(len - numStr.length) + numStr;
                              – ngryman
                              Sep 26 '16 at 21:52


















                            Clearly the most elegant solution I would just modify it to avoid 2 string conversions: const numStr = String(num) and return '0'.repeat(len - numStr.length) + numStr;
                            – ngryman
                            Sep 26 '16 at 21:52






                            Clearly the most elegant solution I would just modify it to avoid 2 string conversions: const numStr = String(num) and return '0'.repeat(len - numStr.length) + numStr;
                            – ngryman
                            Sep 26 '16 at 21:52












                            up vote
                            7
                            down vote













                            I didn't see anyone point out the fact that when you use String.prototype.substr() with a negative number it counts from the right.



                            A one liner solution to the OP's question, a 6-digit zerofilled representation of the number 5, is:






                            console.log(("00000000" + 5).substr(-6));





                            Generalizing we'll get:






                            function pad(num, len) { return ("00000000" + num).substr(-len) };

                            console.log(pad(5, 6));
                            console.log(pad(45, 6));
                            console.log(pad(345, 6));
                            console.log(pad(2345, 6));
                            console.log(pad(12345, 6));








                            share|improve this answer























                            • nice one liner solution
                              – rave
                              Sep 21 '17 at 21:06















                            up vote
                            7
                            down vote













                            I didn't see anyone point out the fact that when you use String.prototype.substr() with a negative number it counts from the right.



                            A one liner solution to the OP's question, a 6-digit zerofilled representation of the number 5, is:






                            console.log(("00000000" + 5).substr(-6));





                            Generalizing we'll get:






                            function pad(num, len) { return ("00000000" + num).substr(-len) };

                            console.log(pad(5, 6));
                            console.log(pad(45, 6));
                            console.log(pad(345, 6));
                            console.log(pad(2345, 6));
                            console.log(pad(12345, 6));








                            share|improve this answer























                            • nice one liner solution
                              – rave
                              Sep 21 '17 at 21:06













                            up vote
                            7
                            down vote










                            up vote
                            7
                            down vote









                            I didn't see anyone point out the fact that when you use String.prototype.substr() with a negative number it counts from the right.



                            A one liner solution to the OP's question, a 6-digit zerofilled representation of the number 5, is:






                            console.log(("00000000" + 5).substr(-6));





                            Generalizing we'll get:






                            function pad(num, len) { return ("00000000" + num).substr(-len) };

                            console.log(pad(5, 6));
                            console.log(pad(45, 6));
                            console.log(pad(345, 6));
                            console.log(pad(2345, 6));
                            console.log(pad(12345, 6));








                            share|improve this answer














                            I didn't see anyone point out the fact that when you use String.prototype.substr() with a negative number it counts from the right.



                            A one liner solution to the OP's question, a 6-digit zerofilled representation of the number 5, is:






                            console.log(("00000000" + 5).substr(-6));





                            Generalizing we'll get:






                            function pad(num, len) { return ("00000000" + num).substr(-len) };

                            console.log(pad(5, 6));
                            console.log(pad(45, 6));
                            console.log(pad(345, 6));
                            console.log(pad(2345, 6));
                            console.log(pad(12345, 6));








                            console.log(("00000000" + 5).substr(-6));





                            console.log(("00000000" + 5).substr(-6));





                            function pad(num, len) { return ("00000000" + num).substr(-len) };

                            console.log(pad(5, 6));
                            console.log(pad(45, 6));
                            console.log(pad(345, 6));
                            console.log(pad(2345, 6));
                            console.log(pad(12345, 6));





                            function pad(num, len) { return ("00000000" + num).substr(-len) };

                            console.log(pad(5, 6));
                            console.log(pad(45, 6));
                            console.log(pad(345, 6));
                            console.log(pad(2345, 6));
                            console.log(pad(12345, 6));






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Sep 21 '17 at 22:16


























                            community wiki





                            2 revs
                            Stephen Quan













                            • nice one liner solution
                              – rave
                              Sep 21 '17 at 21:06


















                            • nice one liner solution
                              – rave
                              Sep 21 '17 at 21:06
















                            nice one liner solution
                            – rave
                            Sep 21 '17 at 21:06




                            nice one liner solution
                            – rave
                            Sep 21 '17 at 21:06










                            up vote
                            6
                            down vote













                            After a, long, long time of testing 15 different functions/methods found in this questions answers, I now know which is the best (the most versatile and quickest).



                            I took 15 functions/methods from the answers to this question and made a script to measure the time taken to execute 100 pads. Each pad would pad the number 9 with 2000 zeros. This may seem excessive, and it is, but it gives you a good idea about the scaling of the functions.



                            The code I used can be found here:
                            https://gist.github.com/NextToNothing/6325915



                            Feel free to modify and test the code yourself.



                            In order to get the most versatile method, you have to use a loop. This is because with very large numbers others are likely to fail, whereas, this will succeed.



                            So, which loop to use? Well, that would be a while loop. A for loop is still fast, but a while loop is just slightly quicker(a couple of ms) - and cleaner.



                            Answers like those by Wilco, Aleksandar Toplek or Vitim.us will do the job perfectly.



                            Personally, I tried a different approach. I tried to use a recursive function to pad the string/number. It worked out better than methods joining an array but, still, didn't work as quick as a for loop.



                            My function is:



                            function pad(str, max, padder) {
                            padder = typeof padder === "undefined" ? "0" : padder;
                            return str.toString().length < max ? pad(padder.toString() + str, max, padder) : str;
                            }


                            You can use my function with, or without, setting the padding variable. So like this:



                            pad(1, 3); // Returns '001'
                            // - Or -
                            pad(1, 3, "x"); // Returns 'xx1'


                            Personally, after my tests, I would use a method with a while loop, like Aleksandar Toplek or Vitim.us. However, I would modify it slightly so that you are able to set the padding string.



                            So, I would use this code:



                            function padLeft(str, len, pad) {
                            pad = typeof pad === "undefined" ? "0" : pad + "";
                            str = str + "";
                            while(str.length < len) {
                            str = pad + str;
                            }
                            return str;
                            }

                            // Usage
                            padLeft(1, 3); // Returns '001'
                            // - Or -
                            padLeft(1, 3, "x"); // Returns 'xx1'


                            You could also use it as a prototype function, by using this code:



                            Number.prototype.padLeft = function(len, pad) {
                            pad = typeof pad === "undefined" ? "0" : pad + "";
                            var str = this + "";
                            while(str.length < len) {
                            str = pad + str;
                            }
                            return str;
                            }

                            // Usage
                            var num = 1;

                            num.padLeft(3); // Returns '001'
                            // - Or -
                            num.padLeft(3, "x"); // Returns 'xx1'





                            share|improve this answer























                            • I put this in a jsfiddle to make it quick for others to test, adding your version of the code: jsfiddle.net/kevinmicke/vnvghw7y/2 Your version is always very competitive, and sometimes the fastest. Thanks for the fairly exhaustive testing.
                              – kevinmicke
                              Oct 5 '15 at 19:17















                            up vote
                            6
                            down vote













                            After a, long, long time of testing 15 different functions/methods found in this questions answers, I now know which is the best (the most versatile and quickest).



                            I took 15 functions/methods from the answers to this question and made a script to measure the time taken to execute 100 pads. Each pad would pad the number 9 with 2000 zeros. This may seem excessive, and it is, but it gives you a good idea about the scaling of the functions.



                            The code I used can be found here:
                            https://gist.github.com/NextToNothing/6325915



                            Feel free to modify and test the code yourself.



                            In order to get the most versatile method, you have to use a loop. This is because with very large numbers others are likely to fail, whereas, this will succeed.



                            So, which loop to use? Well, that would be a while loop. A for loop is still fast, but a while loop is just slightly quicker(a couple of ms) - and cleaner.



                            Answers like those by Wilco, Aleksandar Toplek or Vitim.us will do the job perfectly.



                            Personally, I tried a different approach. I tried to use a recursive function to pad the string/number. It worked out better than methods joining an array but, still, didn't work as quick as a for loop.



                            My function is:



                            function pad(str, max, padder) {
                            padder = typeof padder === "undefined" ? "0" : padder;
                            return str.toString().length < max ? pad(padder.toString() + str, max, padder) : str;
                            }


                            You can use my function with, or without, setting the padding variable. So like this:



                            pad(1, 3); // Returns '001'
                            // - Or -
                            pad(1, 3, "x"); // Returns 'xx1'


                            Personally, after my tests, I would use a method with a while loop, like Aleksandar Toplek or Vitim.us. However, I would modify it slightly so that you are able to set the padding string.



                            So, I would use this code:



                            function padLeft(str, len, pad) {
                            pad = typeof pad === "undefined" ? "0" : pad + "";
                            str = str + "";
                            while(str.length < len) {
                            str = pad + str;
                            }
                            return str;
                            }

                            // Usage
                            padLeft(1, 3); // Returns '001'
                            // - Or -
                            padLeft(1, 3, "x"); // Returns 'xx1'


                            You could also use it as a prototype function, by using this code:



                            Number.prototype.padLeft = function(len, pad) {
                            pad = typeof pad === "undefined" ? "0" : pad + "";
                            var str = this + "";
                            while(str.length < len) {
                            str = pad + str;
                            }
                            return str;
                            }

                            // Usage
                            var num = 1;

                            num.padLeft(3); // Returns '001'
                            // - Or -
                            num.padLeft(3, "x"); // Returns 'xx1'





                            share|improve this answer























                            • I put this in a jsfiddle to make it quick for others to test, adding your version of the code: jsfiddle.net/kevinmicke/vnvghw7y/2 Your version is always very competitive, and sometimes the fastest. Thanks for the fairly exhaustive testing.
                              – kevinmicke
                              Oct 5 '15 at 19:17













                            up vote
                            6
                            down vote










                            up vote
                            6
                            down vote









                            After a, long, long time of testing 15 different functions/methods found in this questions answers, I now know which is the best (the most versatile and quickest).



                            I took 15 functions/methods from the answers to this question and made a script to measure the time taken to execute 100 pads. Each pad would pad the number 9 with 2000 zeros. This may seem excessive, and it is, but it gives you a good idea about the scaling of the functions.



                            The code I used can be found here:
                            https://gist.github.com/NextToNothing/6325915



                            Feel free to modify and test the code yourself.



                            In order to get the most versatile method, you have to use a loop. This is because with very large numbers others are likely to fail, whereas, this will succeed.



                            So, which loop to use? Well, that would be a while loop. A for loop is still fast, but a while loop is just slightly quicker(a couple of ms) - and cleaner.



                            Answers like those by Wilco, Aleksandar Toplek or Vitim.us will do the job perfectly.



                            Personally, I tried a different approach. I tried to use a recursive function to pad the string/number. It worked out better than methods joining an array but, still, didn't work as quick as a for loop.



                            My function is:



                            function pad(str, max, padder) {
                            padder = typeof padder === "undefined" ? "0" : padder;
                            return str.toString().length < max ? pad(padder.toString() + str, max, padder) : str;
                            }


                            You can use my function with, or without, setting the padding variable. So like this:



                            pad(1, 3); // Returns '001'
                            // - Or -
                            pad(1, 3, "x"); // Returns 'xx1'


                            Personally, after my tests, I would use a method with a while loop, like Aleksandar Toplek or Vitim.us. However, I would modify it slightly so that you are able to set the padding string.



                            So, I would use this code:



                            function padLeft(str, len, pad) {
                            pad = typeof pad === "undefined" ? "0" : pad + "";
                            str = str + "";
                            while(str.length < len) {
                            str = pad + str;
                            }
                            return str;
                            }

                            // Usage
                            padLeft(1, 3); // Returns '001'
                            // - Or -
                            padLeft(1, 3, "x"); // Returns 'xx1'


                            You could also use it as a prototype function, by using this code:



                            Number.prototype.padLeft = function(len, pad) {
                            pad = typeof pad === "undefined" ? "0" : pad + "";
                            var str = this + "";
                            while(str.length < len) {
                            str = pad + str;
                            }
                            return str;
                            }

                            // Usage
                            var num = 1;

                            num.padLeft(3); // Returns '001'
                            // - Or -
                            num.padLeft(3, "x"); // Returns 'xx1'





                            share|improve this answer














                            After a, long, long time of testing 15 different functions/methods found in this questions answers, I now know which is the best (the most versatile and quickest).



                            I took 15 functions/methods from the answers to this question and made a script to measure the time taken to execute 100 pads. Each pad would pad the number 9 with 2000 zeros. This may seem excessive, and it is, but it gives you a good idea about the scaling of the functions.



                            The code I used can be found here:
                            https://gist.github.com/NextToNothing/6325915



                            Feel free to modify and test the code yourself.



                            In order to get the most versatile method, you have to use a loop. This is because with very large numbers others are likely to fail, whereas, this will succeed.



                            So, which loop to use? Well, that would be a while loop. A for loop is still fast, but a while loop is just slightly quicker(a couple of ms) - and cleaner.



                            Answers like those by Wilco, Aleksandar Toplek or Vitim.us will do the job perfectly.



                            Personally, I tried a different approach. I tried to use a recursive function to pad the string/number. It worked out better than methods joining an array but, still, didn't work as quick as a for loop.



                            My function is:



                            function pad(str, max, padder) {
                            padder = typeof padder === "undefined" ? "0" : padder;
                            return str.toString().length < max ? pad(padder.toString() + str, max, padder) : str;
                            }


                            You can use my function with, or without, setting the padding variable. So like this:



                            pad(1, 3); // Returns '001'
                            // - Or -
                            pad(1, 3, "x"); // Returns 'xx1'


                            Personally, after my tests, I would use a method with a while loop, like Aleksandar Toplek or Vitim.us. However, I would modify it slightly so that you are able to set the padding string.



                            So, I would use this code:



                            function padLeft(str, len, pad) {
                            pad = typeof pad === "undefined" ? "0" : pad + "";
                            str = str + "";
                            while(str.length < len) {
                            str = pad + str;
                            }
                            return str;
                            }

                            // Usage
                            padLeft(1, 3); // Returns '001'
                            // - Or -
                            padLeft(1, 3, "x"); // Returns 'xx1'


                            You could also use it as a prototype function, by using this code:



                            Number.prototype.padLeft = function(len, pad) {
                            pad = typeof pad === "undefined" ? "0" : pad + "";
                            var str = this + "";
                            while(str.length < len) {
                            str = pad + str;
                            }
                            return str;
                            }

                            // Usage
                            var num = 1;

                            num.padLeft(3); // Returns '001'
                            // - Or -
                            num.padLeft(3, "x"); // Returns 'xx1'






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            answered Aug 24 '13 at 4:12


























                            community wiki





                            Jack B













                            • I put this in a jsfiddle to make it quick for others to test, adding your version of the code: jsfiddle.net/kevinmicke/vnvghw7y/2 Your version is always very competitive, and sometimes the fastest. Thanks for the fairly exhaustive testing.
                              – kevinmicke
                              Oct 5 '15 at 19:17


















                            • I put this in a jsfiddle to make it quick for others to test, adding your version of the code: jsfiddle.net/kevinmicke/vnvghw7y/2 Your version is always very competitive, and sometimes the fastest. Thanks for the fairly exhaustive testing.
                              – kevinmicke
                              Oct 5 '15 at 19:17
















                            I put this in a jsfiddle to make it quick for others to test, adding your version of the code: jsfiddle.net/kevinmicke/vnvghw7y/2 Your version is always very competitive, and sometimes the fastest. Thanks for the fairly exhaustive testing.
                            – kevinmicke
                            Oct 5 '15 at 19:17




                            I put this in a jsfiddle to make it quick for others to test, adding your version of the code: jsfiddle.net/kevinmicke/vnvghw7y/2 Your version is always very competitive, and sometimes the fastest. Thanks for the fairly exhaustive testing.
                            – kevinmicke
                            Oct 5 '15 at 19:17










                            up vote
                            6
                            down vote













                            ECMAScript 2017:
                            use padStart or padEnd



                            'abc'.padStart(10);         // "       abc"
                            'abc'.padStart(10, "foo"); // "foofoofabc"
                            'abc'.padStart(6,"123465"); // "123abc"


                            More info:





                            • https://github.com/tc39/proposal-string-pad-start-end

                            • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart






                            share|improve this answer























                            • Voted up because it works in my scenario and would be nice to have in the specs. (Although it doesn't really answer the question, as it is not about "0"s :-) )
                              – Xan-Kun Clark-Davis
                              Jun 6 '17 at 9:28

















                            up vote
                            6
                            down vote













                            ECMAScript 2017:
                            use padStart or padEnd



                            'abc'.padStart(10);         // "       abc"
                            'abc'.padStart(10, "foo"); // "foofoofabc"
                            'abc'.padStart(6,"123465"); // "123abc"


                            More info:





                            • https://github.com/tc39/proposal-string-pad-start-end

                            • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart






                            share|improve this answer























                            • Voted up because it works in my scenario and would be nice to have in the specs. (Although it doesn't really answer the question, as it is not about "0"s :-) )
                              – Xan-Kun Clark-Davis
                              Jun 6 '17 at 9:28















                            up vote
                            6
                            down vote










                            up vote
                            6
                            down vote









                            ECMAScript 2017:
                            use padStart or padEnd



                            'abc'.padStart(10);         // "       abc"
                            'abc'.padStart(10, "foo"); // "foofoofabc"
                            'abc'.padStart(6,"123465"); // "123abc"


                            More info:





                            • https://github.com/tc39/proposal-string-pad-start-end

                            • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart






                            share|improve this answer














                            ECMAScript 2017:
                            use padStart or padEnd



                            'abc'.padStart(10);         // "       abc"
                            'abc'.padStart(10, "foo"); // "foofoofabc"
                            'abc'.padStart(6,"123465"); // "123abc"


                            More info:





                            • https://github.com/tc39/proposal-string-pad-start-end

                            • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            answered Nov 28 '16 at 8:49


























                            community wiki





                            juFo













                            • Voted up because it works in my scenario and would be nice to have in the specs. (Although it doesn't really answer the question, as it is not about "0"s :-) )
                              – Xan-Kun Clark-Davis
                              Jun 6 '17 at 9:28




















                            • Voted up because it works in my scenario and would be nice to have in the specs. (Although it doesn't really answer the question, as it is not about "0"s :-) )
                              – Xan-Kun Clark-Davis
                              Jun 6 '17 at 9:28


















                            Voted up because it works in my scenario and would be nice to have in the specs. (Although it doesn't really answer the question, as it is not about "0"s :-) )
                            – Xan-Kun Clark-Davis
                            Jun 6 '17 at 9:28






                            Voted up because it works in my scenario and would be nice to have in the specs. (Although it doesn't really answer the question, as it is not about "0"s :-) )
                            – Xan-Kun Clark-Davis
                            Jun 6 '17 at 9:28












                            up vote
                            4
                            down vote













                            The latest way to do this is much simpler:



                            var number = 2
                            number.toLocaleString(undefined, {minimumIntegerDigits:2})


                            output: "02"






                            share|improve this answer























                            • (8).toLocaleString(undefined, {minimumIntegerDigits: 5}) returns "00.008" for me, based on my locale.
                              – le_m
                              Mar 18 '17 at 21:58

















                            up vote
                            4
                            down vote













                            The latest way to do this is much simpler:



                            var number = 2
                            number.toLocaleString(undefined, {minimumIntegerDigits:2})


                            output: "02"






                            share|improve this answer























                            • (8).toLocaleString(undefined, {minimumIntegerDigits: 5}) returns "00.008" for me, based on my locale.
                              – le_m
                              Mar 18 '17 at 21:58















                            up vote
                            4
                            down vote










                            up vote
                            4
                            down vote









                            The latest way to do this is much simpler:



                            var number = 2
                            number.toLocaleString(undefined, {minimumIntegerDigits:2})


                            output: "02"






                            share|improve this answer














                            The latest way to do this is much simpler:



                            var number = 2
                            number.toLocaleString(undefined, {minimumIntegerDigits:2})


                            output: "02"







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            answered Feb 29 '16 at 4:00


























                            community wiki





                            MrE













                            • (8).toLocaleString(undefined, {minimumIntegerDigits: 5}) returns "00.008" for me, based on my locale.
                              – le_m
                              Mar 18 '17 at 21:58




















                            • (8).toLocaleString(undefined, {minimumIntegerDigits: 5}) returns "00.008" for me, based on my locale.
                              – le_m
                              Mar 18 '17 at 21:58


















                            (8).toLocaleString(undefined, {minimumIntegerDigits: 5}) returns "00.008" for me, based on my locale.
                            – le_m
                            Mar 18 '17 at 21:58






                            (8).toLocaleString(undefined, {minimumIntegerDigits: 5}) returns "00.008" for me, based on my locale.
                            – le_m
                            Mar 18 '17 at 21:58












                            up vote
                            4
                            down vote













                            Just an another solution, but I think it's more legible.






                            function zeroFill(text, size)
                            {
                            while (text.length < size){
                            text = "0" + text;
                            }

                            return text;
                            }








                            share|improve this answer























                            • Same as which other?
                              – Fabio Turati
                              Jul 22 '16 at 14:14















                            up vote
                            4
                            down vote













                            Just an another solution, but I think it's more legible.






                            function zeroFill(text, size)
                            {
                            while (text.length < size){
                            text = "0" + text;
                            }

                            return text;
                            }








                            share|improve this answer























                            • Same as which other?
                              – Fabio Turati
                              Jul 22 '16 at 14:14













                            up vote
                            4
                            down vote










                            up vote
                            4
                            down vote









                            Just an another solution, but I think it's more legible.






                            function zeroFill(text, size)
                            {
                            while (text.length < size){
                            text = "0" + text;
                            }

                            return text;
                            }








                            share|improve this answer














                            Just an another solution, but I think it's more legible.






                            function zeroFill(text, size)
                            {
                            while (text.length < size){
                            text = "0" + text;
                            }

                            return text;
                            }








                            function zeroFill(text, size)
                            {
                            while (text.length < size){
                            text = "0" + text;
                            }

                            return text;
                            }





                            function zeroFill(text, size)
                            {
                            while (text.length < size){
                            text = "0" + text;
                            }

                            return text;
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Jul 22 '16 at 14:47


























                            community wiki





                            3 revs
                            Arthur













                            • Same as which other?
                              – Fabio Turati
                              Jul 22 '16 at 14:14


















                            • Same as which other?
                              – Fabio Turati
                              Jul 22 '16 at 14:14
















                            Same as which other?
                            – Fabio Turati
                            Jul 22 '16 at 14:14




                            Same as which other?
                            – Fabio Turati
                            Jul 22 '16 at 14:14










                            up vote
                            4
                            down vote













                            In all modern browsers you can use



                            numberStr.padStart(numberLength, "0");





                            function zeroFill(num, numLength) {
                            var numberStr = num.toString();

                            return numberStr.padStart(numLength, "0");
                            }

                            var numbers = [0, 1, 12, 123, 1234, 12345];

                            numbers.forEach(
                            function(num) {
                            var numString = num.toString();

                            var paddedNum = zeroFill(numString, 5);

                            console.log(paddedNum);
                            }
                            );





                            Here is the MDN reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart






                            share|improve this answer



























                              up vote
                              4
                              down vote













                              In all modern browsers you can use



                              numberStr.padStart(numberLength, "0");





                              function zeroFill(num, numLength) {
                              var numberStr = num.toString();

                              return numberStr.padStart(numLength, "0");
                              }

                              var numbers = [0, 1, 12, 123, 1234, 12345];

                              numbers.forEach(
                              function(num) {
                              var numString = num.toString();

                              var paddedNum = zeroFill(numString, 5);

                              console.log(paddedNum);
                              }
                              );





                              Here is the MDN reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart






                              share|improve this answer

























                                up vote
                                4
                                down vote










                                up vote
                                4
                                down vote









                                In all modern browsers you can use



                                numberStr.padStart(numberLength, "0");





                                function zeroFill(num, numLength) {
                                var numberStr = num.toString();

                                return numberStr.padStart(numLength, "0");
                                }

                                var numbers = [0, 1, 12, 123, 1234, 12345];

                                numbers.forEach(
                                function(num) {
                                var numString = num.toString();

                                var paddedNum = zeroFill(numString, 5);

                                console.log(paddedNum);
                                }
                                );





                                Here is the MDN reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart






                                share|improve this answer














                                In all modern browsers you can use



                                numberStr.padStart(numberLength, "0");





                                function zeroFill(num, numLength) {
                                var numberStr = num.toString();

                                return numberStr.padStart(numLength, "0");
                                }

                                var numbers = [0, 1, 12, 123, 1234, 12345];

                                numbers.forEach(
                                function(num) {
                                var numString = num.toString();

                                var paddedNum = zeroFill(numString, 5);

                                console.log(paddedNum);
                                }
                                );





                                Here is the MDN reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart






                                function zeroFill(num, numLength) {
                                var numberStr = num.toString();

                                return numberStr.padStart(numLength, "0");
                                }

                                var numbers = [0, 1, 12, 123, 1234, 12345];

                                numbers.forEach(
                                function(num) {
                                var numString = num.toString();

                                var paddedNum = zeroFill(numString, 5);

                                console.log(paddedNum);
                                }
                                );





                                function zeroFill(num, numLength) {
                                var numberStr = num.toString();

                                return numberStr.padStart(numLength, "0");
                                }

                                var numbers = [0, 1, 12, 123, 1234, 12345];

                                numbers.forEach(
                                function(num) {
                                var numString = num.toString();

                                var paddedNum = zeroFill(numString, 5);

                                console.log(paddedNum);
                                }
                                );






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                answered Aug 21 '17 at 22:07


























                                community wiki





                                Lifehack























                                    up vote
                                    3
                                    down vote













                                    This one is less native, but may be the fastest...



                                    zeroPad = function (num, count) {
                                    var pad = (num + '').length - count;
                                    while(--pad > -1) {
                                    num = '0' + num;
                                    }
                                    return num;
                                    };





                                    share|improve this answer























                                    • i think you want to do pad = count - (num + '').length. negative numbers aren't handled well, but apart from that, it's not bad. +1
                                      – nickf
                                      Sep 6 '09 at 23:29















                                    up vote
                                    3
                                    down vote













                                    This one is less native, but may be the fastest...



                                    zeroPad = function (num, count) {
                                    var pad = (num + '').length - count;
                                    while(--pad > -1) {
                                    num = '0' + num;
                                    }
                                    return num;
                                    };





                                    share|improve this answer























                                    • i think you want to do pad = count - (num + '').length. negative numbers aren't handled well, but apart from that, it's not bad. +1
                                      – nickf
                                      Sep 6 '09 at 23:29













                                    up vote
                                    3
                                    down vote










                                    up vote
                                    3
                                    down vote









                                    This one is less native, but may be the fastest...



                                    zeroPad = function (num, count) {
                                    var pad = (num + '').length - count;
                                    while(--pad > -1) {
                                    num = '0' + num;
                                    }
                                    return num;
                                    };





                                    share|improve this answer














                                    This one is less native, but may be the fastest...



                                    zeroPad = function (num, count) {
                                    var pad = (num + '').length - count;
                                    while(--pad > -1) {
                                    num = '0' + num;
                                    }
                                    return num;
                                    };






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    answered Sep 6 '09 at 23:05


























                                    community wiki





                                    Jonathan Neal













                                    • i think you want to do pad = count - (num + '').length. negative numbers aren't handled well, but apart from that, it's not bad. +1
                                      – nickf
                                      Sep 6 '09 at 23:29


















                                    • i think you want to do pad = count - (num + '').length. negative numbers aren't handled well, but apart from that, it's not bad. +1
                                      – nickf
                                      Sep 6 '09 at 23:29
















                                    i think you want to do pad = count - (num + '').length. negative numbers aren't handled well, but apart from that, it's not bad. +1
                                    – nickf
                                    Sep 6 '09 at 23:29




                                    i think you want to do pad = count - (num + '').length. negative numbers aren't handled well, but apart from that, it's not bad. +1
                                    – nickf
                                    Sep 6 '09 at 23:29










                                    up vote
                                    3
                                    down vote













                                    My solution



                                    Number.prototype.PadLeft = function (length, digit) {
                                    var str = '' + this;
                                    while (str.length < length) {
                                    str = (digit || '0') + str;
                                    }
                                    return str;
                                    };


                                    Usage



                                    var a = 567.25;
                                    a.PadLeft(10); // 0000567.25

                                    var b = 567.25;
                                    b.PadLeft(20, '2'); // 22222222222222567.25





                                    share|improve this answer



























                                      up vote
                                      3
                                      down vote













                                      My solution



                                      Number.prototype.PadLeft = function (length, digit) {
                                      var str = '' + this;
                                      while (str.length < length) {
                                      str = (digit || '0') + str;
                                      }
                                      return str;
                                      };


                                      Usage



                                      var a = 567.25;
                                      a.PadLeft(10); // 0000567.25

                                      var b = 567.25;
                                      b.PadLeft(20, '2'); // 22222222222222567.25





                                      share|improve this answer

























                                        up vote
                                        3
                                        down vote










                                        up vote
                                        3
                                        down vote









                                        My solution



                                        Number.prototype.PadLeft = function (length, digit) {
                                        var str = '' + this;
                                        while (str.length < length) {
                                        str = (digit || '0') + str;
                                        }
                                        return str;
                                        };


                                        Usage



                                        var a = 567.25;
                                        a.PadLeft(10); // 0000567.25

                                        var b = 567.25;
                                        b.PadLeft(20, '2'); // 22222222222222567.25





                                        share|improve this answer














                                        My solution



                                        Number.prototype.PadLeft = function (length, digit) {
                                        var str = '' + this;
                                        while (str.length < length) {
                                        str = (digit || '0') + str;
                                        }
                                        return str;
                                        };


                                        Usage



                                        var a = 567.25;
                                        a.PadLeft(10); // 0000567.25

                                        var b = 567.25;
                                        b.PadLeft(20, '2'); // 22222222222222567.25






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        answered Dec 27 '12 at 17:15


























                                        community wiki





                                        Aleksandar Toplek























                                            up vote
                                            3
                                            down vote













                                            Not that this question needs more answers, but I thought I would add the simple lodash version of this.



                                            _.padLeft(number, 6, '0')






                                            share|improve this answer



















                                            • 1




                                              Better: var zfill = _.partialRight(_.padStart, '0');
                                              – Droogans
                                              Mar 14 '16 at 18:03






                                            • 2




                                              Some people will probably protest "I don't want to use lodash" but it's hardly a valid argument anymore since you can install only this function: npm install --save lodash.padleft, then import padLeft from 'lodash.padleft' and omit the _.
                                              – Andy
                                              Oct 14 '16 at 20:44

















                                            up vote
                                            3
                                            down vote













                                            Not that this question needs more answers, but I thought I would add the simple lodash version of this.



                                            _.padLeft(number, 6, '0')






                                            share|improve this answer



















                                            • 1




                                              Better: var zfill = _.partialRight(_.padStart, '0');
                                              – Droogans
                                              Mar 14 '16 at 18:03






                                            • 2




                                              Some people will probably protest "I don't want to use lodash" but it's hardly a valid argument anymore since you can install only this function: npm install --save lodash.padleft, then import padLeft from 'lodash.padleft' and omit the _.
                                              – Andy
                                              Oct 14 '16 at 20:44















                                            up vote
                                            3
                                            down vote










                                            up vote
                                            3
                                            down vote









                                            Not that this question needs more answers, but I thought I would add the simple lodash version of this.



                                            _.padLeft(number, 6, '0')






                                            share|improve this answer














                                            Not that this question needs more answers, but I thought I would add the simple lodash version of this.



                                            _.padLeft(number, 6, '0')







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            answered Jul 13 '15 at 15:21


























                                            community wiki





                                            Art









                                            • 1




                                              Better: var zfill = _.partialRight(_.padStart, '0');
                                              – Droogans
                                              Mar 14 '16 at 18:03






                                            • 2




                                              Some people will probably protest "I don't want to use lodash" but it's hardly a valid argument anymore since you can install only this function: npm install --save lodash.padleft, then import padLeft from 'lodash.padleft' and omit the _.
                                              – Andy
                                              Oct 14 '16 at 20:44
















                                            • 1




                                              Better: var zfill = _.partialRight(_.padStart, '0');
                                              – Droogans
                                              Mar 14 '16 at 18:03






                                            • 2




                                              Some people will probably protest "I don't want to use lodash" but it's hardly a valid argument anymore since you can install only this function: npm install --save lodash.padleft, then import padLeft from 'lodash.padleft' and omit the _.
                                              – Andy
                                              Oct 14 '16 at 20:44










                                            1




                                            1




                                            Better: var zfill = _.partialRight(_.padStart, '0');
                                            – Droogans
                                            Mar 14 '16 at 18:03




                                            Better: var zfill = _.partialRight(_.padStart, '0');
                                            – Droogans
                                            Mar 14 '16 at 18:03




                                            2




                                            2




                                            Some people will probably protest "I don't want to use lodash" but it's hardly a valid argument anymore since you can install only this function: npm install --save lodash.padleft, then import padLeft from 'lodash.padleft' and omit the _.
                                            – Andy
                                            Oct 14 '16 at 20:44






                                            Some people will probably protest "I don't want to use lodash" but it's hardly a valid argument anymore since you can install only this function: npm install --save lodash.padleft, then import padLeft from 'lodash.padleft' and omit the _.
                                            – Andy
                                            Oct 14 '16 at 20:44












                                            up vote
                                            3
                                            down vote













                                            Why not use recursion?



                                            function padZero(s, n) {
                                            s = s.toString(); // in case someone passes a number
                                            return s.length >= n ? s : padZero('0' + s, n);
                                            }





                                            share|improve this answer























                                            • padZero(223, 3) fails with '0223'
                                              – Serginho
                                              Oct 18 '16 at 10:55










                                            • Well, I assumed that this function is called with a string as the first parameter. However, I fixed it.
                                              – lex82
                                              Oct 18 '16 at 12:12












                                            • I love recursions :-)
                                              – Xan-Kun Clark-Davis
                                              Jun 6 '17 at 9:33















                                            up vote
                                            3
                                            down vote













                                            Why not use recursion?



                                            function padZero(s, n) {
                                            s = s.toString(); // in case someone passes a number
                                            return s.length >= n ? s : padZero('0' + s, n);
                                            }





                                            share|improve this answer























                                            • padZero(223, 3) fails with '0223'
                                              – Serginho
                                              Oct 18 '16 at 10:55










                                            • Well, I assumed that this function is called with a string as the first parameter. However, I fixed it.
                                              – lex82
                                              Oct 18 '16 at 12:12












                                            • I love recursions :-)
                                              – Xan-Kun Clark-Davis
                                              Jun 6 '17 at 9:33













                                            up vote
                                            3
                                            down vote










                                            up vote
                                            3
                                            down vote









                                            Why not use recursion?



                                            function padZero(s, n) {
                                            s = s.toString(); // in case someone passes a number
                                            return s.length >= n ? s : padZero('0' + s, n);
                                            }





                                            share|improve this answer














                                            Why not use recursion?



                                            function padZero(s, n) {
                                            s = s.toString(); // in case someone passes a number
                                            return s.length >= n ? s : padZero('0' + s, n);
                                            }






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Oct 18 '16 at 12:12


























                                            community wiki





                                            2 revs
                                            lex82













                                            • padZero(223, 3) fails with '0223'
                                              – Serginho
                                              Oct 18 '16 at 10:55










                                            • Well, I assumed that this function is called with a string as the first parameter. However, I fixed it.
                                              – lex82
                                              Oct 18 '16 at 12:12












                                            • I love recursions :-)
                                              – Xan-Kun Clark-Davis
                                              Jun 6 '17 at 9:33


















                                            • padZero(223, 3) fails with '0223'
                                              – Serginho
                                              Oct 18 '16 at 10:55










                                            • Well, I assumed that this function is called with a string as the first parameter. However, I fixed it.
                                              – lex82
                                              Oct 18 '16 at 12:12












                                            • I love recursions :-)
                                              – Xan-Kun Clark-Davis
                                              Jun 6 '17 at 9:33
















                                            padZero(223, 3) fails with '0223'
                                            – Serginho
                                            Oct 18 '16 at 10:55




                                            padZero(223, 3) fails with '0223'
                                            – Serginho
                                            Oct 18 '16 at 10:55












                                            Well, I assumed that this function is called with a string as the first parameter. However, I fixed it.
                                            – lex82
                                            Oct 18 '16 at 12:12






                                            Well, I assumed that this function is called with a string as the first parameter. However, I fixed it.
                                            – lex82
                                            Oct 18 '16 at 12:12














                                            I love recursions :-)
                                            – Xan-Kun Clark-Davis
                                            Jun 6 '17 at 9:33




                                            I love recursions :-)
                                            – Xan-Kun Clark-Davis
                                            Jun 6 '17 at 9:33










                                            up vote
                                            2
                                            down vote













                                            Some monkeypatching also works



                                            String.prototype.padLeft = function (n, c) {
                                            if (isNaN(n))
                                            return null;
                                            c = c || "0";
                                            return (new Array(n).join(c).substring(0, this.length-n)) + this;
                                            };
                                            var paddedValue = "123".padLeft(6); // returns "000123"
                                            var otherPadded = "TEXT".padLeft(8, " "); // returns " TEXT"





                                            share|improve this answer



















                                            • 1




                                              -1 monkeypatching the toplevel namespacing in javascript is bad practice.
                                              – Jeremy Wall
                                              Sep 7 '09 at 0:37






                                            • 2




                                              True for Object and Array objects, but String is not bad
                                              – Rodrigo
                                              Sep 11 '09 at 16:56















                                            up vote
                                            2
                                            down vote













                                            Some monkeypatching also works



                                            String.prototype.padLeft = function (n, c) {
                                            if (isNaN(n))
                                            return null;
                                            c = c || "0";
                                            return (new Array(n).join(c).substring(0, this.length-n)) + this;
                                            };
                                            var paddedValue = "123".padLeft(6); // returns "000123"
                                            var otherPadded = "TEXT".padLeft(8, " "); // returns " TEXT"





                                            share|improve this answer



















                                            • 1




                                              -1 monkeypatching the toplevel namespacing in javascript is bad practice.
                                              – Jeremy Wall
                                              Sep 7 '09 at 0:37






                                            • 2




                                              True for Object and Array objects, but String is not bad
                                              – Rodrigo
                                              Sep 11 '09 at 16:56













                                            up vote
                                            2
                                            down vote










                                            up vote
                                            2
                                            down vote









                                            Some monkeypatching also works



                                            String.prototype.padLeft = function (n, c) {
                                            if (isNaN(n))
                                            return null;
                                            c = c || "0";
                                            return (new Array(n).join(c).substring(0, this.length-n)) + this;
                                            };
                                            var paddedValue = "123".padLeft(6); // returns "000123"
                                            var otherPadded = "TEXT".padLeft(8, " "); // returns " TEXT"





                                            share|improve this answer














                                            Some monkeypatching also works



                                            String.prototype.padLeft = function (n, c) {
                                            if (isNaN(n))
                                            return null;
                                            c = c || "0";
                                            return (new Array(n).join(c).substring(0, this.length-n)) + this;
                                            };
                                            var paddedValue = "123".padLeft(6); // returns "000123"
                                            var otherPadded = "TEXT".padLeft(8, " "); // returns " TEXT"






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            answered Sep 7 '09 at 0:07


























                                            community wiki





                                            Rodrigo









                                            • 1




                                              -1 monkeypatching the toplevel namespacing in javascript is bad practice.
                                              – Jeremy Wall
                                              Sep 7 '09 at 0:37






                                            • 2




                                              True for Object and Array objects, but String is not bad
                                              – Rodrigo
                                              Sep 11 '09 at 16:56














                                            • 1




                                              -1 monkeypatching the toplevel namespacing in javascript is bad practice.
                                              – Jeremy Wall
                                              Sep 7 '09 at 0:37






                                            • 2




                                              True for Object and Array objects, but String is not bad
                                              – Rodrigo
                                              Sep 11 '09 at 16:56








                                            1




                                            1




                                            -1 monkeypatching the toplevel namespacing in javascript is bad practice.
                                            – Jeremy Wall
                                            Sep 7 '09 at 0:37




                                            -1 monkeypatching the toplevel namespacing in javascript is bad practice.
                                            – Jeremy Wall
                                            Sep 7 '09 at 0:37




                                            2




                                            2




                                            True for Object and Array objects, but String is not bad
                                            – Rodrigo
                                            Sep 11 '09 at 16:56




                                            True for Object and Array objects, but String is not bad
                                            – Rodrigo
                                            Sep 11 '09 at 16:56










                                            up vote
                                            2
                                            down vote













                                            function pad(toPad, padChar, length){
                                            return (String(toPad).length < length)
                                            ? new Array(length - String(toPad).length + 1).join(padChar) + String(toPad)
                                            : toPad;
                                            }


                                            pad(5, 0, 6) = 000005



                                            pad('10', 0, 2) = 10 // don't pad if not necessary



                                            pad('S', 'O', 2) = SO



                                            ...etc.



                                            Cheers






                                            share|improve this answer























                                            • This doesn't work. pad(100, '0', 4) => 000100
                                              – drewish
                                              May 22 '12 at 20:23










                                            • I think it should be more like: var s = String(toPad); return (s.length < length) ? new Array(length - s.length + 1).join('0') + s : s; if you fix it I'll remove my down vote.
                                              – drewish
                                              May 22 '12 at 20:24












                                            • @drewish Thanks for catching that, I agree with your edit (except for the hardcoded 0 join char :) -- Answer updated.
                                              – Madbreaks
                                              May 22 '12 at 21:25










                                            • Ah yeah I'd hard coded it in my usage.
                                              – drewish
                                              May 23 '12 at 2:04










                                            • I think it'd be better to store the string into a temporary variable. I did some benchmarking of that here: jsperf.com/padding-with-memoization it's also got benchmarks for the use of the new in "new Array" the results for new are all over the place but memiozation seems like the way to go.
                                              – drewish
                                              May 23 '12 at 16:28















                                            up vote
                                            2
                                            down vote













                                            function pad(toPad, padChar, length){
                                            return (String(toPad).length < length)
                                            ? new Array(length - String(toPad).length + 1).join(padChar) + String(toPad)
                                            : toPad;
                                            }


                                            pad(5, 0, 6) = 000005



                                            pad('10', 0, 2) = 10 // don't pad if not necessary



                                            pad('S', 'O', 2) = SO



                                            ...etc.



                                            Cheers






                                            share|improve this answer























                                            • This doesn't work. pad(100, '0', 4) => 000100
                                              – drewish
                                              May 22 '12 at 20:23










                                            • I think it should be more like: var s = String(toPad); return (s.length < length) ? new Array(length - s.length + 1).join('0') + s : s; if you fix it I'll remove my down vote.
                                              – drewish
                                              May 22 '12 at 20:24












                                            • @drewish Thanks for catching that, I agree with your edit (except for the hardcoded 0 join char :) -- Answer updated.
                                              – Madbreaks
                                              May 22 '12 at 21:25










                                            • Ah yeah I'd hard coded it in my usage.
                                              – drewish
                                              May 23 '12 at 2:04










                                            • I think it'd be better to store the string into a temporary variable. I did some benchmarking of that here: jsperf.com/padding-with-memoization it's also got benchmarks for the use of the new in "new Array" the results for new are all over the place but memiozation seems like the way to go.
                                              – drewish
                                              May 23 '12 at 16:28













                                            up vote
                                            2
                                            down vote










                                            up vote
                                            2
                                            down vote









                                            function pad(toPad, padChar, length){
                                            return (String(toPad).length < length)
                                            ? new Array(length - String(toPad).length + 1).join(padChar) + String(toPad)
                                            : toPad;
                                            }


                                            pad(5, 0, 6) = 000005



                                            pad('10', 0, 2) = 10 // don't pad if not necessary



                                            pad('S', 'O', 2) = SO



                                            ...etc.



                                            Cheers






                                            share|improve this answer














                                            function pad(toPad, padChar, length){
                                            return (String(toPad).length < length)
                                            ? new Array(length - String(toPad).length + 1).join(padChar) + String(toPad)
                                            : toPad;
                                            }


                                            pad(5, 0, 6) = 000005



                                            pad('10', 0, 2) = 10 // don't pad if not necessary



                                            pad('S', 'O', 2) = SO



                                            ...etc.



                                            Cheers







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited May 23 '12 at 3:50


























                                            community wiki





                                            Madbreaks













                                            • This doesn't work. pad(100, '0', 4) => 000100
                                              – drewish
                                              May 22 '12 at 20:23










                                            • I think it should be more like: var s = String(toPad); return (s.length < length) ? new Array(length - s.length + 1).join('0') + s : s; if you fix it I'll remove my down vote.
                                              – drewish
                                              May 22 '12 at 20:24












                                            • @drewish Thanks for catching that, I agree with your edit (except for the hardcoded 0 join char :) -- Answer updated.
                                              – Madbreaks
                                              May 22 '12 at 21:25










                                            • Ah yeah I'd hard coded it in my usage.
                                              – drewish
                                              May 23 '12 at 2:04










                                            • I think it'd be better to store the string into a temporary variable. I did some benchmarking of that here: jsperf.com/padding-with-memoization it's also got benchmarks for the use of the new in "new Array" the results for new are all over the place but memiozation seems like the way to go.
                                              – drewish
                                              May 23 '12 at 16:28


















                                            • This doesn't work. pad(100, '0', 4) => 000100
                                              – drewish
                                              May 22 '12 at 20:23










                                            • I think it should be more like: var s = String(toPad); return (s.length < length) ? new Array(length - s.length + 1).join('0') + s : s; if you fix it I'll remove my down vote.
                                              – drewish
                                              May 22 '12 at 20:24












                                            • @drewish Thanks for catching that, I agree with your edit (except for the hardcoded 0 join char :) -- Answer updated.
                                              – Madbreaks
                                              May 22 '12 at 21:25










                                            • Ah yeah I'd hard coded it in my usage.
                                              – drewish
                                              May 23 '12 at 2:04










                                            • I think it'd be better to store the string into a temporary variable. I did some benchmarking of that here: jsperf.com/padding-with-memoization it's also got benchmarks for the use of the new in "new Array" the results for new are all over the place but memiozation seems like the way to go.
                                              – drewish
                                              May 23 '12 at 16:28
















                                            This doesn't work. pad(100, '0', 4) => 000100
                                            – drewish
                                            May 22 '12 at 20:23




                                            This doesn't work. pad(100, '0', 4) => 000100
                                            – drewish
                                            May 22 '12 at 20:23












                                            I think it should be more like: var s = String(toPad); return (s.length < length) ? new Array(length - s.length + 1).join('0') + s : s; if you fix it I'll remove my down vote.
                                            – drewish
                                            May 22 '12 at 20:24






                                            I think it should be more like: var s = String(toPad); return (s.length < length) ? new Array(length - s.length + 1).join('0') + s : s; if you fix it I'll remove my down vote.
                                            – drewish
                                            May 22 '12 at 20:24














                                            @drewish Thanks for catching that, I agree with your edit (except for the hardcoded 0 join char :) -- Answer updated.
                                            – Madbreaks
                                            May 22 '12 at 21:25




                                            @drewish Thanks for catching that, I agree with your edit (except for the hardcoded 0 join char :) -- Answer updated.
                                            – Madbreaks
                                            May 22 '12 at 21:25












                                            Ah yeah I'd hard coded it in my usage.
                                            – drewish
                                            May 23 '12 at 2:04




                                            Ah yeah I'd hard coded it in my usage.
                                            – drewish
                                            May 23 '12 at 2:04












                                            I think it'd be better to store the string into a temporary variable. I did some benchmarking of that here: jsperf.com/padding-with-memoization it's also got benchmarks for the use of the new in "new Array" the results for new are all over the place but memiozation seems like the way to go.
                                            – drewish
                                            May 23 '12 at 16:28




                                            I think it'd be better to store the string into a temporary variable. I did some benchmarking of that here: jsperf.com/padding-with-memoization it's also got benchmarks for the use of the new in "new Array" the results for new are all over the place but memiozation seems like the way to go.
                                            – drewish
                                            May 23 '12 at 16:28










                                            up vote
                                            2
                                            down vote













                                            The simplest, most straight-forward solution you will find.



                                            function zerofill(number,length) {
                                            var output = number.toString();
                                            while(output.length < length) {
                                            output = '0' + output;
                                            }
                                            return output;
                                            }





                                            share|improve this answer



























                                              up vote
                                              2
                                              down vote













                                              The simplest, most straight-forward solution you will find.



                                              function zerofill(number,length) {
                                              var output = number.toString();
                                              while(output.length < length) {
                                              output = '0' + output;
                                              }
                                              return output;
                                              }





                                              share|improve this answer

























                                                up vote
                                                2
                                                down vote










                                                up vote
                                                2
                                                down vote









                                                The simplest, most straight-forward solution you will find.



                                                function zerofill(number,length) {
                                                var output = number.toString();
                                                while(output.length < length) {
                                                output = '0' + output;
                                                }
                                                return output;
                                                }





                                                share|improve this answer














                                                The simplest, most straight-forward solution you will find.



                                                function zerofill(number,length) {
                                                var output = number.toString();
                                                while(output.length < length) {
                                                output = '0' + output;
                                                }
                                                return output;
                                                }






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                answered Jan 7 '15 at 9:22


























                                                community wiki





                                                d4nyll























                                                    1 2
                                                    3
                                                    next




                                                    protected by Ionică Bizău Dec 2 '14 at 18:19



                                                    Thank you for your interest in this question.
                                                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                    Would you like to answer one of these unanswered questions instead?



                                                    Popular posts from this blog

                                                    Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                                                    Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

                                                    A Topological Invariant for $pi_3(U(n))$