views:

3336

answers:

3

Duplicate of this one.

What would you use to pad zeroes to the left of a number in Flex/AS3?

Is there an equivalent to printf or NumberFormat that does this?

I'm looking for the nicest implementation of this or something similar:

public function zeroPad(number:int, width:int):String {
    // number = 46, width = 4 would return "0046"
}
+8  A: 
public function zeroPad(number:int, width:int):String {
   var ret:String = ""+number;
   while( ret.length < width )
       ret="0" + ret;
   return ret;
}
Phil
A: 

I do maintain a printf in AS3: Unfortunately stack overflow won't let me post links, but if the google code's project name is printf-as3

Feedback is always welcome.

--

http://code.google.com/p/printf-as3/

Arthur Debert
A: 
/** 
 * originally by Chris Agiasotis @ http://agitatedobserver.com/as3-currency-formatter/
 * improved by Joseph Balderson @ http://www.joeflash.ca
 */
package
{
    public class CurrencyFormat
    {
     public function CurrencyFormat(){ }

     public function getCurrency(num:Number,
        decimalSeparator:String=".",
        decimalPlace:Number=2,
        currency:String="$",
        thousandsSeparator:String=","
       ):String
     {
      //assigns true boolean value to neg in number less than 0
      var neg:Boolean = (num < 0);

      //make the number positive for easy conversion
      num = Math.abs(num)

      var roundedAmount:String = String(num.toFixed(decimalPlace));

      //split string into array for dollars and cents
      var amountArray:Array = roundedAmount.split(".");
      var dollars:String = amountArray[0]
      var cents:String = amountArray[1]

      //create dollar amount
      var dollarFinal:String = ""
      var i:int = 0
      for (i; i < dollars.length; i++)
      {
       if (i > 0 && (i % 3 == 0 ))
       {
        dollarFinal = thousandsSeparator + dollarFinal;
       }

       dollarFinal = dollars.substr( -i -1, 1) + dollarFinal;
      } 

      //create Cents amount and zeros if necessary
      var centsFinal:String = String(cents);

      var missingZeros:int = decimalPlace - centsFinal.length;

      if (centsFinal.length < decimalPlace)
      {
       for (var j:int = 0; j < missingZeros; j++) 
       {
        centsFinal += "0";
       }
      }

      var finalString:String = ""

      if (neg)
      {
       finalString = "-"+currency + dollarFinal
      } else
      {
       finalString = currency + dollarFinal
      }

      if(decimalPlace > 0)
      {
       finalString += decimalSeparator + centsFinal;
      } 

      return finalString;
     }
    }
}
Joeflash