[ Team LiB ] |
Recipe 5.4 Inserting Leading or Trailing Zeros5.4.1 ProblemYou want to add leading or trailing zeros to a number to display it as a string. 5.4.2 SolutionCreate a custom Math.zeroFill( ) method. 5.4.3 DiscussionYou 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:
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):
Here's the custom zeroFill( ) method that you can add to your Math.as 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 "Math.as" val = 42; trace(val.toString(2)); // Displays: "101010" trace(Math.zeroFill(val.toString(2), 8)); // Displays: "00101010" 5.4.4 See AlsoRecipe 5.2 and Recipe 5.6 |
[ Team LiB ] |