Archive for the ‘ActionScript’ Category


AS2 / AS3 Game Score Formatter


Published in: ActionScript, ActionScript 3Posted by Jeremy on 09/11/08


Often when developing games I have the need to add zeros in front of my score depending on how many digits are to be shown. For instance, even though I may have a score of 5, I still need to display 00005 on the screen.

To do this I wrote this useful little function for just that purpose.

trace(formatScore(555, 6)); // 000555 trace(formatScore(-555, 6)); // -000555

function formatScore( value:Number, digits):String {

var scoreStr:String = ''; var tempScore:String = '';

var scoreLen:Number = value.toString().length; var indexOfNeg:Number = value.toString().indexOf('-');

if (value.toString().charAt(0) == '-') {

tempScore = String(value.toString().substring(indexOfNeg+1, scoreLen)); scoreLen--; } for (var i:Number = 0; i<(digits-scoreLen); i++) {

scoreStr += '0'; } var posAnswer:String = String(scoreStr+value.toString()); var negAnswer:String = '-'+String(scoreStr+tempScore.toString()); var answer:String = (indexOfNeg == -1) ? posAnswer : negAnswer;

return answer; }

Jeremy Sykes is a Flash Game Programmer & Developer