O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required