views:

91

answers:

2

Newbie ActionScript 3 question: why does

(Math.sqrt((r * r - (r - i) * (r - i)) as Number) * 2) as int

give me a different result from

int(Math.sqrt((r * r - (r - i) * (r - i)) as Number) * 2)
+7  A: 

The as operator is a direct cast, whereas int() implicitly finds the floor of the Number (note that it doesn't actually call Math.floor, though). The Adobe docs for as say it checks that the "first operand is a member of the data type specified by the second operand." Since 9.59 is not representable as an int, the as cast fails a returns null, while int() first finds the floor of the number, then casts it to int.

You could do Math.floor(blah) as int, and it should work, though it would be slower. Assuming you want a rounded int, Math.round(blah) as int would be more correct, but int(blah + .5) would be fastest and round correctly.

mercilor
+1  A: 

The as operator is not much as a cast, more something like:

i is int ? int : null;

This is confusing as hell. It checks if the variable is of that type, if it is, the variable is returned, else you'd get null (0 for an int).

Arthur Debert