Interpreting a String as a Number
Flash CS4 ActionScript 3.0 Tutorial
How to Temporarily Convert a String to a Number
Variables are assigned a specific data type. Some of the variable options are, Strings (letters and numbers), Booleans (true or false), Numbers (numbers with decimal places), ints (whole numbers) or uints (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 gather data, convert the data and process the information.
Input Text object with instance name inText_txt
Button Symbol with instance name submit_btn
Static Text box with text, To calculate the square, enter a value and press Submit
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 one block of Input text. Choose Input text In the Properties panel.
Using Static text, add the phrase, To calculate the square, enter a value and press Submit
Click the Input text box and assign it an instance name of inText_txt in the Properties panel. Also active the text box borders.
Add a button symbol to the Content layer and assign it an instance name of submit_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.
inText_txt.restrict = "0-9";
Click the Auto Format button to format the code
Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Input a number and press the Submit button. The square value appears in the Output panel.
Dissecting the Code
The first line establishes a Number variable with an initial value of zero. The second line restricts the user's input values to 0 through 9. In other words, no letters are allowed.
The next line adds an Event Listener to the button. It needs to know if the button has been clicked. Once the user enters a value and clicks the button, the function showSquare is told to run. The function interprets the String value as a Number and passes it to totalValue. Then totalValue is squared and displayed in the Output panel.