Wednesday, January 5, 2011

ActionScript 3 Number to String Conversion

In this lesson, we're going to learn how to convert numbers to strings in AS3.

If you you'd like to do ActionScript 3 Number to String conversions, then you can use the toString() method of the Number class.

Here is an example:
var myNumber:Number = 7;
var myString:String = myNumber.toString();
Here, we start off by creating a number - myNumber with a value of 7. In the next line, that number is converted into a string and is assigned to a variable named myString.

Why would I want to convert numbers to strings?
One example of how this can be useful is if you'd like to calculate some number value and then display it inside a text field.

For example:
var value1:Number = 7;
var value2:Number = 2;
var total:Number = value1 + value2;

myTextField.text =  total.toString();
// Assume that myTextField is an instance of the TextField class
// and that it has already been created and added to the stage
Here, we're creating two numbers (7 and 2), which are then added together (which sums up to 9). The sum is then displayed inside a text field. Without the toString() method, Flash will give us an error message if we try to assign a Number value inside the text field. The error message will state:
1067: Implicit coercion of a value of type Number to an unrelated type String.
This means that we are trying to force a number to be a string. A text field can not contain Number data so we will have to convert it to a String instead. Although, 9 as a Number looks the same as "9" as a String, you must still explicitly differentiate between the two inside your ActionScript 3 code. This makes AS3 number to string conversions pretty useful.
 
If the number is a decimal (e.g. .5), Flash will add a leading 0 when it performs the number to string conversion (i.e. .5 will become "0.5").

Also, the toString() method of the Number class accepts one parameter for the radix. The radix lets you specify which numeric base (from 2 to 36) to use when the number is converted into a string. For example, if you'd like the number to be interpreted as an octal (base 8), then you pass a value of 8 to the radix parameter:
var myNumber:Number = 14;
trace( myNumber.toString(8) );
If we used base 10, then this will still output 14. But since we specified base 8 instead, this will output 16. If no radix is specified, a default value of 10 (decimal) is used.

So that is how you do ActionScript 3 number to string conversions.

No comments:

Post a Comment