1

Is there a smart way to convert numbers to string and automatically add zeroes so the length is the same as the maximum?

like this:

for (var i=0; i<30; i++) {
    var c = i.toString();
    if (c.length == 1) {
        c = '0'+=c;
    }
}

But smarter

David Hellsing
  • 106,495
  • 44
  • 176
  • 212
  • 2
    possible duplicate of [How to output integers with leading zeros in JavaScript](http://stackoverflow.com/questions/2998784/how-to-output-integers-with-leading-zeros-in-javascript) – kennytm Jun 09 '10 at 15:47

10 Answers10

4

I think the fastest way to do it is without the loop. Like that:

var pad="000000";
var str="182"; //or any desired number here

var result=pad.slice(str.length)+str;

Result will be 000182. Let me know.

Michael

steveax
  • 17,527
  • 6
  • 44
  • 59
Michael
  • 41
  • 1
4

There's a million ways, this is one of them, and its actually quite efficient too..

UPDATE 2 Here's code for the 'third interpretation of the OP's question

This will output ["00", "01", "02" .... ,"30"]

var max = 30, i = max, maxLength = max.toString().length, num,  zeroes=[];
while (i--) zeroes.push("0");
zeroes = zeroes.join();

for (i=0; i < max ; i++) {
    num = i.toString();
    console.log(zeroes.substring(0, maxLength - num.length) + num);
}

UPDATE 1 adapted the code for both 'possible' interpretations of the OP's question.

If what you want is code that based on n=5 , max = 30 produces 29 "0"s followed by "5" then this is the code you want

var n = 5, max = 30;

var a = n.toString().split(), zeroesToAdd = max - a.length;
while(zeroesToAdd--) a.unshift("0");
var num = a.join("");

alert(num);​

If what you want is code that based on n=5 , max = 30 produces 2 (the length of 30.toString()) "0"s followed by "5" then this is the code you want

var n = 5, maxLength = (30).toString().length;

var a = n.toString().split(), zeroesToAdd = maxLength - a.length;
while(zeroesToAdd--) a.unshift("0");
var num = a.join("");

alert(num);​

The only difference here is in the first line.

These do not use string concatenation (extremely inefficient), instead they use Array.unshift and Array.join

Sean Kinsey
  • 37,689
  • 7
  • 52
  • 71
  • This is definitely clever, but I'm under the impression that you are adding 30 "0"s, wouldn't max need to be 2 (the number of places)? – sworoc Jun 09 '10 at 15:18
  • No, I'm adding 29 (30 - "5".length). This is according to the OP's request as far as I can see – Sean Kinsey Jun 09 '10 at 15:29
  • What's the purpose of the `split()` there? Doesn't that just return the original input right back? (I know this is a small nitpick to a great answer; using `unshift()` here is brilliant.) – Pops Jun 09 '10 at 15:35
  • Firebug seems to be showing 29 leading zeros given the code above. Otherwise, nice work! – sworoc Jun 09 '10 at 15:36
  • @sworoc Now, isn't the point of this to return a string the length of `max`? If so 29 "0"s and "5" is pretty much the correct answer isn't it? – Sean Kinsey Jun 09 '10 at 15:39
  • @Lord It creates an array from the string, with each character in its own slot – Sean Kinsey Jun 09 '10 at 15:39
  • I believe he's trying to print out the numbers 0 through 29, zero padded (single digit numbers have 1 leading 0). I think it's just a misreading of his loop that is causing issue. His code and yours produce different output, though I agree that yours works in the general case. – sworoc Jun 09 '10 at 15:40
1

I'm not entirely sure I understand what you mean by "smarter," but I did find this flexible zero-padding method (slightly modified due to @Sean's comment; in-code comments mine):

function PadDigits(n, totalDigits)
{
    n = n.toString();
    var pd = '';
    // Figure out if we need to pad at all
    if (totalDigits > n.length)
    {
        // Construct a string of as many leading zeroes as needed
        for (i = 0; i < (totalDigits-n.length); i++)
        {
            pd += '0'; // String concat for EACH leading zero; inefficient
        }
    }
    // Add the leading zeroes to the string representing the original number
    return pd + n; // Removed unnecessary toString() here
}

Source: http://classicasp.aspfaq.com/general/how-do-i-pad-digits-with-leading-zeros.html

Pops
  • 30,199
  • 37
  • 136
  • 151
1

you could ask mr. google for a javascript implementation of sprintf() wich might be useful in some other cases - but if you only have to do this one operation, such a function will be a bit too much overhead.

oezi
  • 51,017
  • 10
  • 98
  • 115
0
for (var i=0; i<30; i++)
  var c = i < 10 ? '0'+i.toString() : i.toString() ;
Romain Deveaud
  • 824
  • 5
  • 11
  • What would you do if it was a 5 character field (10,000)? How do you account for zero padding 100? 1000? – sworoc Jun 09 '10 at 15:05
  • The loop given by the op is only between 0 and 30. – Romain Deveaud Jun 09 '10 at 15:10
  • True, but smarter implies not needing to rewrite the whole thing to do 0 to 100, and in this case you would need two checks, one for < 10 and one for < 100. Just sayin' – sworoc Jun 09 '10 at 15:13
0
var c=i.toString(), len=30-c.length;
while(len>0){
   c='0'+c;
   --len;
  }
kennebec
  • 102,654
  • 32
  • 106
  • 127
0
var zeroPad = "000";

for(var i=0; i<30; i++) {
 var output = zeroPad + i.toString();
 output.substr(output.length - 2);
}

If you vary the number of "0" in zeroPad, and change your length offset, this will work for however large you want (obviously within reason). Not the best, but it works and is simple.

sworoc
  • 1,461
  • 12
  • 13
0

here is how to do it (parametric)

// number is the number you need to convert, and maxdigits is the total number of digits including the number
function leadingZeros( number, maxdigits )
{
 var number_text = number.toString();
 var number_len = number_text.length;

 for (var i=0;i<maxdigits-number_len;i++)
     number_text = '0'+number_text;

 return number_text;
}
// example leadingZeros(3,5)   will return 00003
// example leadingZeros(194,5) will return 00194
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
0

With courtesy from 4GuysFromRolla, for those used to VBScript:

var padd = "000000000000000000000000000000";
var sourceval = 100;

alert(Right(padd + sourceval, 30));

function Right(str, n)
{
    if (n <= 0)
    {
        return "";
    }

    if (n > String(str).length)
    {
        return str;
    }

    var iLen = String(str).length;
    return String(str).substring(iLen, iLen - n);
}
Filburt
  • 17,626
  • 12
  • 64
  • 115
  • @nico Definitly not the best shot - @InfinitiesLoop has a better solution: http://stackoverflow.com/questions/2998784/how-to-output-integers-with-leading-zeros-in-javascript/2998822#2998822 ... and @CMS does also have a good one: http://stackoverflow.com/questions/2998784/how-to-output-integers-with-leading-zeros-in-javascript/2998874#2998874 I didn't flex that JavaScript muscle for quite some time ... – Filburt Jun 10 '10 at 06:51
0

If you are trying to determine how many digits you will need, do a ceiling(log10) of the maximum number you are converting to a string, and that will tell you, assuming you don't have anything to the right of the decimal point.

whatsisname
  • 5,872
  • 2
  • 20
  • 27