At some point using Actionscript 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.
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 as3 class to a folder relative to your flash document /com/frigidfish/utils/PadZero.as
Here is an example usage:
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:
// 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. Have fun experimenting with Flash Actionscript 3!