5.4. Inserting Leading or Trailing Zeros

Problem

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

Solution

Create a custom Math.zeroFill( ) method.

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):

num

The number you want to format.

places

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

trailing

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 Math.as ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.