tags:

views:

151

answers:

9

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

A: 
for (var i=0; i<30; i++)
  var c = i < 10 ? '0'+i.toString() : i.toString() ;
Romain Deveaud
What would you do if it was a 5 character field (10,000)?How do you account for zero padding 100? 1000?
sworoc
The loop given by the op is only between 0 and 30.
Romain Deveaud
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
+1  A: 

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

Lord Torgamus
Not too efficient, also, for some reason it calls toString twice on n
Sean Kinsey
A: 
var c=i.toString(), len=30-c.length;
while(len>0){
   c='0'+c;
   --len;
  }
kennebec
`while(i--) { }` is a simpler approach, especially since you aren't using `i` for anything inside the block
Sean Kinsey
A: 
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
A: 

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
Gaby
+1  A: 

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
+4  A: 

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
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
No, I'm adding 29 (30 - "5".length). This is according to the OP's request as far as I can see
Sean Kinsey
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.)
Lord Torgamus
Firebug seems to be showing 29 leading zeros given the code above. Otherwise, nice work!
sworoc
@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
@Lord It creates an array from the string, with each character in its own slot
Sean Kinsey
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
A: 

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
Looks very VB-style in effect...
nico
@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#2998874I didn't flex that JavaScript muscle for quite some time ...
Filburt
@Filburt: no worries, I was just joking! :)
nico
A: 

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