0

I have always used the NumberFormat class in Java to do simple number padding ie. turn 1, 2, 3... into 0001, 0002, 0003....

Is there a similar utility in ActionScript to do my padding, or will I have to write a custom function?

adam
  • 22,404
  • 20
  • 87
  • 119

2 Answers2

4

Seems there is nothing built in. This will do it:

function padZero (num:Number, digits:int):String {
  var ret:String = num.toString();
  while (ret.length < digits)
    ret = "0" + ret;
  return ret;
}

Though com.adobe.utils.NumberFormatter has addLeadingZero(n:Number):String, which sounds promising, but according to the spec it pads a single zero to numbers between -1 and 10. I guess the function is useful for time output only.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
1

Flash now has the NumberFormatter() class as part of flash.globalization.*

it will format numbers in the users locale

http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/globalization/NumberFormatter.html

you can also set the number of leading, or trailing zeros

rszemeti
  • 91
  • 2
  • Thanks for updating this! Since this question is also a Flex question, it's worth noting that there is also a [spark.formatters.NumberFormatter](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/formatters/NumberFormatter.html), which wraps the class you referenced and also provides fallback support for those OS's that don't support the `flash.globalization.NumberFormatter` methods. – merv Oct 19 '11 at 19:30