Bits & Bytes

Type Conversions of Primitive Types in Actionscript

We can perform explicit type conversions by using constructor notation like this:

var dFloat:Number = 3.14159;
var iConv:int = int(dFloat);

Here, we have the conversion of a floating-point (Number) type to an integer (int) type. A conversion from a Number to an int truncates the decimal so that the converted value “qConv” holds the value 3 after these lines are executed. In general, this is how the Number type gets converted to an int or a uint type: the value is simply truncated at the decimal point.

The Number type holds a much wider range than either the uint or int type can hold. When a Number type variable’s value lies outside the range of an int or a uint and a conversion takes place, a truncation occurs and the value is wrapped until it lies in the range of the target type.

var dFloat:Number = -3.14159;
var uiConv:uint = uint(dFloat);

In the example above, the negative value of “dFloat” lies outside the range of the uint type. So, the result of this conversion is 4294967293, which is the same value you would get if you converted an int with the value of -3 to the unsigned (uint) type.

var bBool:Boolean = true;
var uiConv:uint = uint(bBool);

We can convert numbers to booleans and vice versa. A Boolean variable with the value true gets converted to 1 and the value false gets converted to 0. This is the case regardless of whether the number type we are converting to is a uint, int or Number. So, the code segment above results in “uiConv” taking on the value 1 after the conversion.

var iNeg:int = -1;
var bConv:Boolean = Boolean(iNeg);

When converting to a Boolean type from a numerical type, the value 0 converts to false, as does the value NaN for Number type variables. All other numerical values convert to true. So, for example, the code above converts the value -1 to true.

Converting numerical types to a String is pretty straight-forward. The value is converted to a string representation of the number. Likewise, Boolean values are converted to the strings “true” or “false,” as expected.

var sString:String = "a3.14";
var dConv:Number = Number(sString);

However, converting values from a String type is somewhat strange. A String converts to a Boolean value of false if the String is null or empty (“”). Otherwise, it converts to true. A String converts to a number if it can be converted. If a String contains non-numeric characters it converts to 0 for int and uint types, but converts to NaN for a Number type. The code above converts the string “a3.14” to NaN.

Tags: , , , , , , , , ,

Michael Hall

By: Michael Hall

Leave a Reply

*

 

© 2007–2024 XoaX.net LLC. All rights reserved.