Interpreting a String as a Number

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.

Tutorial Elements

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

 

Step One

Open a new Flash document and add a new layer.

Step Two

Name the upper layer Actions and the lower layer Content.

Step Three

Click the keyframe for the Content layer.

Step Four

Add one block of Input text. Choose Input text In the Properties panel.

Step Five

Using Static text, add the phrase, To calculate the square, enter a value and press Submit

Step Six

Click the Input text box and assign it an instance name of inText_txt in the Properties panel. Also active the text box borders.

Step Seven

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.

Step Eight

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

Step Nine

Copy/Paste the following code to the ActionScript panel.

var totalValue:Number=0

inText_txt.restrict = "0-9";

submit_btn.addEventListener(MouseEvent.CLICK, showSquare);

function showSquare(e:MouseEvent):void{

totalValue=Number(inText_txt.text);

totalValue=totalValue*totalValue;

trace(totalValue);

}

Step Ten

Click the Auto Format button to format the code

Step Eleven

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.

 

Lynda.com career skills