5.6. Formatting Currency Amounts
Problem
You want to format a number as currency, such as dollars.
Solution
Create a custom Math.currencyFormat( ) method.
Discussion
Unlike some other languages, such as ColdFusion, ActionScript does not have a built-in function for formatting numbers as currency amounts. That’s the bad news. The good news is that it is not too difficult to create a custom method to format numbers as currency amounts.
Our custom Math.currencyFormat( ) method accepts
up to seven parameters:
-
num The number to format.
-
decimalPl The number of decimal places in the formatted number.
-
currencySymbol The symbol, such as a dollar sign ($), to use.
-
thousandsDelim The characters used to delimit thousands, millions, etc.
-
decimalDelim The characters used to delimit the fractional portion from the whole number.
-
truncate If
true, truncate the number to the specified number of decimal places; otherwise, round the number.-
spaceFill The number of spaces the entire formatted string should occupy.
Here is our custom Math.currencyFormat( )
method. The method converts a numeric parameter into a
currency-formatted string. Include this method within
Math.as along with the custom
roundDecPl( ), numberFormat(
), and zeroFill( ) methods in this
chapter, on which this example relies.
Math.currencyFormat = function (num, decimalPl, currencySymbol, thousandsDelim, decimalDelim, truncate, spaceFill) { // Default to two decimal places, a dollar sign ($), a comma for thousands, and a // period for the ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access