Recipe 5.4 Inserting Leading or Trailing Zeros

5.4.1 Problem

You want to add leading or trailing zeros to a number to display it as a string.

5.4.2 Solution

Create a custom Math.zeroFill( ) method.

5.4.3 Discussion

You might need to format numbers with leading or trailing zeros for display purposes, such as when displaying times or dates. For example, you would want to format 6 hours and 3 minutes as 6:03 or 06:03, not 6:3. And when you display monetary values, you often want to ensure that two digits appear after the decimal place so that 23 dollars and 40 cents is formatted as $24.40, not $23.4.

To add leading zeros, follow these steps:

  1. Convert the number into a string using the String( ) function.

  2. Determine the number of zeros to add by subtracting the string length from the number of places you want in the resulting value.

  3. Use a for loop to prepend the necessary number of zeros (as strings) to the number.

To add trailing zeros, follow the same steps, but append the zeros instead of prepending them.

You can define a custom method, Math.zeroFill( ), to format a number with leading or trailing zeros and invoke it whenever it is needed.

The Math.zeroFill( ) method accepts up to three parameters (it returns a string):


The number you want to format.


The number of total digits that should be filled in the resulting, formatted numeric string.


If true, then the zeros are appended to the string. Otherwise, the zeros are prepended.

Here's the custom zeroFill( ) method that you can add to your file for easy inclusion in any Flash movie:

Math.zeroFill = function (num, places, trailing) {

  // Convert the number to a string.
  var filledVal = String(num);

  // Get the length of the string.
  var len = filledVal.length;

  // Use a for statement to add the necessary number of characters.
  for (var i = 0; i < (places - len); i++) {
    // If trailing is true, append the zeros; otherwise, prepend them.
    if (trailing) {
      filledVal += "0";
    } else {
      filledVal = "0" + filledVal;
  // Return the string.
  return filledVal;

Here is an example that uses zeroFill( ) to display the binary representation of a number. The first trace( ) statement simply displays the value returned by Number.toString( ). The second trace( ) statement displays the zero-filled version showing all eight bits of the number instead of just six.

#include ""
val = 42;
trace(val.toString(2));                      // Displays: "101010"
trace(Math.zeroFill(val.toString(2), 8));    // Displays: "00101010"

5.4.4 See Also

Recipe 5.2 and Recipe 5.6

    Part I: Local Recipes
    Part II: Remote Recipes