0

I can't figure out how to solve the following problem.

  • I have an array of numbers from 1 to 100.
  • I need to convert them to strings but to a length of 5.

So, for instance:

1 becomes 00001
2 becomes 00002
3 becomes 00003
4 becomes 00004
etc, etc..

It seems so easy but I cannot find a function. The best I found was .toFixed(n) which is the number of decimal points to use.

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Andrew Simpson
  • 6,883
  • 11
  • 79
  • 179
  • Here is an easy way that I didn't manage to post as an answer before the question was closed: http://jsfiddle.net/Guffa/5K9sw/ – Guffa Oct 28 '13 at 15:43
  • to: Phillip, t.J. Crowder, Adma Barmar and Yoshi. Hi, thanks for that additional link. Did not see it on my travels. Bit confused as there is a comment stating not to use it because it is memory intensive? What is ur opinion pls? Thanks – Andrew Simpson Oct 28 '13 at 16:30
  • That solution is memory intensive because it creates an array to create a string of a specific length. An efficient way is if you can use a predefined string with the maximum number of digits, like in the example that I posted, then the code only creates two intermediate strings (the leading zeroes and the string form of the number). You could even set up an array of strings with different length to use for different padding, doing that would take it down to a single intermediate string, but then there is an initial cost of creating that array. – Guffa Oct 28 '13 at 17:03
  • Thanks for the explanation. It was more of why the question was marked as duplicate when it did not really led to an answer I could use. the info I got from your good self and @h2oooooo are answer that can be used. Thank you. – Andrew Simpson Oct 28 '13 at 18:40

1 Answers1

2

Here's a very simple padding function:

function padLeft(str, length, paddingCharacter) {
    str = '' + str; //Make sure that we convert it to a string if it isn't

    while (str.length < length) {
        str = paddingCharacter + str; //Pad it
    }

    return str;
}

padLeft(123, 5, '0'); //00123
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
  • thank u v much. That did it :). I have to wait 8 minutes before I can accept your answer for some reason. Thank you so much for helping me.. – Andrew Simpson Oct 28 '13 at 15:41