1

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)
unwind
  • 391,730
  • 64
  • 469
  • 606
Archagon
  • 2,470
  • 2
  • 25
  • 38
  • Well... what 2 results do you get? – Marc Gravell Jun 04 '09 at 08:07
  • 9.59... without any casting to int, 9 with the second one, and 0 for the first one. – Archagon Jun 04 '09 at 08:16
  • I did some more testing, and apparently (9 as int), (9.5 as Number), and (int(9.5)) give the correct results, but (9.5 as int) results in null. Why would this be the case? – Archagon Jun 04 '09 at 08:23
  • Hmm! This user had a similar problem: http://www.flexer.info/2008/01/11/cast-to-int-issue/ I was under the impression that the two casting methods were nearly equivalent. Is this even mentioned anywhere in the ActionScript documentation?! – Archagon Jun 04 '09 at 08:28
  • This question really does need more up votes. – Panzercrisis Sep 18 '13 at 21:34

2 Answers2

8

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.

Andrew Champion
  • 549
  • 4
  • 10
2

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
  • 10,237
  • 5
  • 26
  • 21