Algorithm for adding leading zeros

I’ve always been writing this.

		function addZero(n:int):String {
			if (n < 10) {
				return "0" + n;
			}else {
				return "" + n;
			}
		}

The function adds one leading 0 quite well but if two 0 is needed, it's quite bad to write all the conditions to check whether it's less than 100 or 10. I think the following code is more efficient.


		function addZero(n:int, numZeros:int = 1):String {
			var str:String = n + "";
			while (str.length<numZeros+1)
			{
				str = "0" + str;
			}
			return str;
		}
  1. fabbrikk

    Hi, I think you have forgot the return statement.

    function addZero(n:int, numZeros:int = 1):String {
    var str:String = n + “”;
    while (str.length<numZeros+1)
    {
    str = “0″ + str;
    }
    return str;
    }

  2. Fernando

    You arguments should be unsigned int or otherwise you will end up with smth like: “000-10″.

    My try would be:

    function addZero(n:uint, numZeros:uint):String{
    return (new Array(numZeros).join(”0″)) + n;
    }

    Cheers!

  3. 5566

    @Fernando, I will blame the programmer whoever tries to pass “-1″ in to add zeros in front of it. It’s pointless to use uint either. It’ll end up as a very big integer.

    Anyway, very cool algorithm. Smarter than mine, definitely!

  4. Mozart Petter

    I think that a good solution is this:

    function addLeadingZeros(n:Number, q:Number):String
    {
    return Math.pow(10, q – n.toString().length).toString().substr(1) + n;
    }

    Without the unnecessary loop. :)

    Cheers

  5. Ed

    Adding a little bit to @Fernandos post. You need to add 1 to the number of zeros to join to make it come out to the correct number. I also made it so that the number of zeros to add defaults to 1.

    public static function addLeadingZero(n:int, numZeros:int = 1):String
    {
    return (new Array(numZeros + 1).join(’0′)) + n as String;
    }

Leave a Reply

For spam filtering purposes, please copy the number 4812 to the field below: