Number Parsing in ActionScript
In ActionScript, parsing numbers from strings is a common task. Here’s how to do it:
package {
import flash.display.Sprite;
import flash.text.TextField;
public class NumberParsing extends Sprite {
public function NumberParsing() {
var output:TextField = new TextField();
output.width = 400;
output.height = 300;
addChild(output);
// Parse a float
var f:Number = parseFloat("1.234");
output.appendText(f + "\n");
// Parse an integer
var i:int = parseInt("123");
output.appendText(i + "\n");
// Parse a hexadecimal number
var d:int = parseInt("0x1c8", 16);
output.appendText(d + "\n");
// Parse an unsigned integer
var u:uint = uint("789");
output.appendText(u + "\n");
// Parse a string to an integer
var k:int = int("135");
output.appendText(k + "\n");
// Handle parsing errors
try {
var invalid:int = int("wat");
} catch (e:Error) {
output.appendText(e.message + "\n");
}
}
}
}
In ActionScript, we use built-in functions for number parsing:
parseFloat()
is used to parse floating-point numbers.parseInt()
is used to parse integers. It can also parse hexadecimal numbers when specifying the radix (base) as 16.uint()
is used to parse unsigned integers.int()
is a convenience function for parsing integers.
Unlike some other languages, ActionScript doesn’t have separate functions for parsing different integer sizes. The int
type is always 32-bit, and uint
is used for unsigned 32-bit integers.
To handle parsing errors, we use a try-catch block. If the parsing fails, an error will be thrown.
To run this code, you would typically compile it into a SWF file and run it in a Flash Player or AIR runtime environment. The output would be displayed in a TextField on the stage.
Next, we’ll look at another common parsing task: URLs.