Section 14.7. Unit Conversions

14.7. Unit Conversions

AppleScript provides a number of classes whose sole purpose is to allow you to perform measurement unit conversions. They are implemented as classes so that you can use the as operator to perform the conversion; that is, the conversion is really a coercion.

Because of this implementation, the way you have to speak in order to perform a conversion ends up looking fairly silly. You can't say 3 feet; you have to coerce 3 (a number) to the feet class, by saying 3 as feet. Now you coerce to the desired class; suppose this is yards. But now you have a value of the yards class. You can't do anything with it, so you have to coerce it to a number (or a string). So, for example:

 on feetToYards(ft)     return ft as feet as yards as number end feetToYards feetToYards(3) -- 1.0 

The implemented units are themselves a mixed lot. Many important units, such as acres and hectares, aren't implemented at all. Accuracy of some of the conversions has also been called into question, but this is said to be fixed in Tiger. Table 14-1 provides a list.

Table 14-1. Conversion unit classes








square meters

square feet

square yards

square miles

square kilometers




cubic meters

cubic centimeters

cubic feet

cubic inches

cubic yards





degrees Celsius

degrees Fahrenheit

degrees Kelvin


A better list of conversion units is built into Mac OS X by way of the Unix tool units. Here's a way to use it:

 on convert(val, unit1, unit2)     set text item delimiters to " "     set conv to do shell script ({"units", unit1, unit2} as string)     return val * (word 1 of paragraph 1 of conv as real) end convert convert(4, "feet", "meters") -- 1.2192 

AppleScript. The Definitive Guide
AppleScript: The Definitive Guide, 2nd Edition
ISBN: 0596102119
EAN: 2147483647
Year: 2006
Pages: 267
Authors: Matt Neuburg

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: