Home > Blog > AS3 Helper Class – Pad String with Zeroes

AS3 Helper Class – Pad String with Zeroes

We are building an AS3 Helper class to speed up development on Actionscript 3 projects. Feel free to use these methods in your own Helper class, or to share your own methods that you find useful.

PadStringWithZeroes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Helper
{
	/**
	 * Add a number of leading zeroes in front of a string.
	 * totalDigits specifies the total number of characters you want to see
	 * in the returned string.
	 */	
	public static function PadStringWithZeroes(string:String, totalDigits:uint):String
	{
		var zeroString:String = "";
		for (var i:uint = 0; i < totalDigits - string.length; i++)
		{
			zeroString += "0";
		}
		return zeroString + string;
	}			
}

Usage

1
var paddedNumber:String = Helper.PadStringWithZeroes(String(5), 4); // returns "0005"

Comments

We use this one most often for scores, where you want to see 00000010 instead of 10. Having all of those leading zeroes in there shows the player there’s something to work up to, and it mimics classic arcade conventions like pinball machine scores.

For more AS3 Helper Classses and a pile of other useful stuff, check out our Flash and Actionscript 911 feature.

Ryan Henson Creighton is a Toronto-based game developer, and founder of Untold Entertainment Inc., specializing in online games for kids, teens, tweens and preschoolers.
Ryan Henson Creighton
Ryan Henson Creighton
View all posts by Ryan Henson Creighton

Popularity: 5% [?]

Rate this Post:
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...
                      

                                 
 

2 Responses to “AS3 Helper Class – Pad String with Zeroes”

  1. awesome tutorial, I unfortunately can’t get it to work in CS3. I’ve created the helper class, and it loads in properly, I however get an error on line 9 of the class. The error is 1026: Constructor functions must be instance methods.

    I’m not sure what I am doing incorrectly, any help would be appreciated.

    • Thanks, jpitkin. That error can crop up due to a number of different things. The good news is that most of them are silly, and you can just move one or two things around to fix the problem.

      Make sure that your Helper class follows the proper structure that we lay out in this post:

      Understanding Classes in AS3 Part 1

      And feel free to paste your code in a pastebin site and share it here if you’re still having problems.

      - Ryan

Leave a Reply