At some point you may need to display a number that must always occupy a predetermined number of character spaces. An example would be a rolling game timer with a 5 digit display. For example, when the timer hits 33 seconds, the digits would display like so: 0 0 0 3 3
It is very simple to pad your number to whatever length of characters you would like.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | package com.frigidfish.utils{ public class PadZero { public static function convert(inputNumber:Number,numberOfDigits:int):String { var paddedString:String=inputNumber.toString(); while (paddedString.length < numberOfDigits) { paddedString = "0" + paddedString; } return paddedString; } } } |
Save this class to a folder relative to your flash document /com/frigidfish/utils/PadZero.as
Here is an example usage:
1 2 3 4 | import com.frigidfish.utils.PadZero; trace(PadZero.convert(33,5)); // traces 00033 |
I use this little converter all the time with customized timers and counters.
If you would like a simple example of a timer, you could do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // Simple Counter // Add 4 text boxes to the stage. // Name their instances from left to right: // digit0, digit1, digit2, digit3 import com.frigidfish.utils.PadZero import flash.utils.Timer; import flash.events.TimerEvent; var counter:int = 0; var timer:Timer = new Timer(1000); timer.addEventListener(TimerEvent.TIMER, addOne); timer.start(); function addOne(event:TimerEvent):void{ counter ++; if(counter > 9999) counter = 0; var t:String = PadZero.convert(counter,4); digit0.text = t.charAt(0); digit1.text = t.charAt(1); digit2.text = t.charAt(2); digit3.text = t.charAt(3); } |
You could make custom digits with your own artwork to spice up your timer.






