Feeds



Share Snipplr

del.icio.us Digg Furl Reddit

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

Tags:

Comments

RSS Icon Subscribe to comments
Posted By: pear on October 4th, 2008

I took a look at this code and it looked pretty complicated to me. I mean, it looks nice, but I came up with a shorter way.
function format(num:Number, digits:Number) {
var answer;
for (var i = 0; i<(digits-num.toString().length); i++) {
if (i == 0) {
answer = “0″;
} else {
answer += “0″;
}
}
answer += num;
return answer;
}
Just felt like sharing…

Posted By: Jason on October 15th, 2008

Heres an even shorter (and recursive) soloution (in javascript):

function addZeros(score,digits) {
if(score.length >= digits) { return score; }
return addZeros(“0″+score,digits);
}

Call with `addZeros((549).toString(),7);`

Will return `”0000549″`

Posted By: Jim on April 22nd, 2009

Neither shorter answer takes the negative value into account… I don’t know Flash/ActionScript, but this pseudo code suggests the original could be much cleaner:

addZeros( score, digits ) {
var prefix = “”;
if( score < 0 ) {
prefix = “-”;
score = -score;
}
for( i = abs(score).toString().length; i < digits; i++ ) {
prefix += “0″;
}
return prefix + score;
}

Posted By: Jim on April 22nd, 2009

Oops, left the abs() in, but the score = -score takes care of that.

Leave a Reply




You may use Markdown to format your comment.
HTML renders as source code.