views:

1536

answers:

6

I have a number in Javascript, that I know is less than 10000. I want to display it as a four-digit number, with leading zeroes. Is there anything more elegant than the following?

if(num<10) num="000"+num;
else if(num<100) num="00"+num;
else if(num<1000) num="0"+num;

I want something that is built into Javascript, but I can't seem to find anything.

+2  A: 

I don't know of anything more elegant than that - I'm not aware of any built in support from any common libraries and I don't see much of a performance hit from that

PSU_Kardi
+5  A: 

I don't think there's anything "built" into the JavaScript language for doing this. Here's a simple function that does this:

function FormatNumberLength(num, length) {
    var r = "" + num;
    while (r.length < length) {
        r = "0" + r;
    }
    return r;
}


FormatNumberLength(10000, 5) outputs '10000'
FormatNumberLength(1000, 5)  outputs '01000'
FormatNumberLength(100, 5)   outputs '00100'
FormatNumberLength(10, 5)    outputs '00010'
Chris Pietschmann
I would prefer to call num.toString() method.
SolutionYogi
+3  A: 

This might help :

String.prototype.padLeft = function (length, character) { 
     return new Array(length - this.length + 1).join(character || '0') + this; 
}

var num = '12';

alert(num.padLeft(4, '0'));
Canavar
A: 

You could go crazy with methods like these:

function PadDigits(input, totalDigits) 
{ 
    var result = input;
    if (totalDigits > input.length) 
    { 
        for (i=0; i < (totalDigits - input.length); i++) 
        { 
            result = '0' + result; 
        } 
    } 
    return result;
}

But it won't make life easier. C# has a method like PadLeft and PadRight in the String class, unfortunately Javascript doesn't have this functionality build-in

Zyphrax
A: 

How about something like this:

function prefixZeros(number, maxDigits) 
{  
    var length = maxDigits - number.toString().length;
    if(length <= 0)
     return number;

    var leadingZeros = new Array(length + 1);
    return leadingZeros.join('0') + number.toString();
}
//Call it like prefixZeros(100, 5); //Alerts 00100
SolutionYogi
+1  A: 

A funny (but interesting) way to prefix numbers with zeros:

function FormatInteger(num, length) {

    return (num / Math.pow(10, length)).toFixed(length).substr(2);
}
Soubok