Number, String, and Date Coercions

An integer may be coerced to a real .

A real (within in the integer range) may be coerced to an integer; it is rounded to the nearest integer. This was a new feature starting in Panther; in earlier versions of AppleScript, a real could be coerced to an integer only if it was an integer (that is, it had no fractional part). The old behavior is still present in repeat with (see Chapter 19) and, as you'll see in a moment, in coercion from a string (I regard this as a bug).

Warning

Observe that AppleScript's real-to-integer coercion rule is not like that of other computer languages you may know, such as in C, where the fractional part is thrown away. To throw away the fractional part of x, say x div 1 (see Chapter 15). The round scripting addition command can also help here (see "Numbers and Dates" in Chapter 21), as it can be used to dictate the desired rounding behavior.

A number may be coerced to a string.

A string may be coerced to a number, provided that the string looks like a literal number; whitespace will be ignored, but nothing else will be. So for example "1a" can't be coerced to a number. But the empty string, or a string consisting solely of whitespace, will be coerced to 0.

Distinguish between the classes integer and real, on the one hand, and number on the other. A string may be coerced to a real, provided that the string looks like a number. A string may be coerced to an integer, though, only if the string looks like an integer value: ...

Get AppleScript: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.