If you’re thinking “I know what an int is”, you need to take this little quiz to find out for sure!

Have a look at this tiny AS3 app and think about what each type() line prints: Number or int?

	import flash.display.*;
	import flash.utils.*;
	import flash.text.*;
	public class IntAndNumber extends Sprite
		public function IntAndNumber()
			var logger:TextField = new TextField();
			logger.autoSize = TextFieldAutoSize.LEFT;
			function type(name:String, val:*): void {
				logger.appendText(name + ": " + describeType(val).@name + "\n");
			var i:int = 2;
			var n:Number = 2.3;
			var ni:Number = 2;
			type("1", 1);
			type("1.0", 1.0);
			type("1.00000000001", 1.00000000001);
			type("1.000000000001", 1.000000000001);
			type("1.0000000000001", 1.0000000000001);
			type("1.00000000000001", 1.00000000000001);
			type("1.000000000000001", 1.000000000000001);
			type("1.0000000000000001", 1.0000000000000001);
			type("i", i);
			type("n", n);
			type("ni", ni);
			type("1+1", 1+1);
			type("i+1", i+1);
			type("n+1", n+1);
			type("ni+1", ni+1);
			type("1.0+1.0", 1.0+1.0);
			type("i+1.0", i+1.0);
			type("n+1.0", n+1.0);
			type("ni+1.0", ni+1.0);
			type("i+i", i+i);
			type("i+n", i+n);
			type("i+ni", i+ni);
			type("n+ni", n+ni);

Now see how many you got correct:

1: int
1.0: int
1.00000000001: Number
1.000000000001: Number
1.0000000000001: Number
1.00000000000001: Number
1.000000000000001: Number
1.0000000000000001: int
i: int
n: Number
ni: int
1+1: int
i+1: int
n+1: Number
ni+1: int
1.0+1.0: int
i+1.0: int
n+1.0: Number
ni+1.0: int
i+i: int
i+n: Number
i+ni: int
n+ni: Number

Did you get them all? I suspect that many programmers will be thrown for a loop by these common misconceptions:

  • A Number variable is actually an int if its value is a whole number
  • Adding .0 to a literal does not make it a Number
  • Adding two int values does not result in a Number that must be casted back when used as an Array index
  • Literal floating-point values can be silently converted to int: beware!

As you use Number and int in your AS3 apps, keep these behaviors in mind. If you find you’ve forgotten one of the more subtle points, the above should serve as a handy reference.

Know any more oddities about Number and int? Leave a comment!