Formatting Numbers

Formatting Numbers

Flash CS4 ActionScript 3.0 Tutorial

 

How to Format Numbers by Setting Decimal Precision with Flash ActionScript

 

 

You may need to display a number with a specific decimal places or display the number with certain precision. In this example we will use the toPrecision() and toFixed() methods to evaluate the variables. Both methods produce String output values. The toFixed() method is handy when working with currency with two decimal values.

 

Step One

Open a new document and change the layer name to Actions.

Step Two

Option double-click (PC - Alt double click) the first keyframe of the Actions layer to open the ActionScript panel.

Step Three

Copy/Paste the following code in the ActionScript Panel:

var a:Number=40.175;

var b:Number=5.2258;

trace(a.toFixed(2) + " " + typeof(a.toFixed(2)));

trace(b.toPrecision(4) + " " + typeof(a.toPrecision(4)));

Step Four

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). The new values for a and b appear in the Output window along with their data type.

Dissecting the Code

The first two lines establish new variables (a and b) and sets a value for each. The next line sets a to a value with two decimal places and displays its data type.

The final line sets the precision value to 4 characters for the b variable. The output value displays as a String in the Output panel. Notice that 5.2258 is rounded up to 5.226.