Interpreting a Number as a String
Flash CS4 ActionScript 3.0 Tutorial
How to Temporarily Convert a Number to a String
Variables are assigned a specific data type. Some of the variable options are, String (letters and numbers), Boolean (true or false), Number (numbers with decimal places), int (whole numbers) or uint (positive whole numbers). Dynamic or Input text only accept String values.
If you attempt to gather a Number from the user, process it with ActionScript and then return a value, the data type must be converted twice. In this example we will make a number calculation with ActionScript, convert it to a String, then display the String value in a Dynamic Text box.
Dynamic Text object with instance name outText_txt
Button Symbol with instance name roll_btn
Static Text box with text, Press Roll button for new random number
Open a new Flash document and add a new layer.
Name the upper layer Actions and the lower layer Content.
Click the keyframe for the Content layer.
Add an empty Dynamic text block. Choose Dynamic text In the Properties panel.
Using Static text, add the phrase, Press Roll button for new random number.
Click the Dynamic text box and assign it an instance name of outText_txt in the Properties panel.
Add a button symbol to the Content layer and assign it an instance name of roll_btn in the Properties panel. For more information on creating buttons, see topic, Button Symbol Basics.
Option double-click (PC - Alt double-click) the keyframe of the Actions layer to open the ActionScript panel.
Copy/Paste the following code to the ActionScript panel.
var rollValue:uint = 0
rollValue = 100*Math.random();
outText_txt.text = String(rollValue);
Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Each time you press the Roll button, a new random number displays in the Dynamic text field.
Dissecting the Code
The first line of code establishes a new positive integer variable named rollValue and sets its value to zero. The next line adds an Event Listener to the button. It needs to know if the button has been clicked. Once the user clicks the button, the function newRoll is told to run.
The code inside the function's curly braces determines what the function will do. The rollValue line creates a random number between zero and one. That number is multiplied by 100 so your random values are whole numbers between zero and 100.
The final line of code interprets the rollValue as a String and places that value in the Dynamic text field with the instance name of outText_txt.
Other Ways to Interpret a Number as a String
In this example we used the code String(rollValue) to interpret the uint (unsigned integer) as a string. A dynamic text field can only display string values. You could also used either one of the following code samples to accomplish the same thing.
rollValue + "";