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.
So, for example:
on feetToYards(ft)
return ft as feet as yards as number
end feetToYards
feetToYards(3) -- 1.0The implemented units are themselves a mixed lot. Many important units, such as acres and hectares, aren’t implemented at all. Table 14-1 provides a list.
Table 14-1. Conversion unit classes
|
meters |
inches |
feet |
yards |
|
miles |
kilometers |
centimeters |
square meters |
|
square feet |
square yards |
square miles |
square kilometers |
|
liters |
gallons |
quarts |
cubic meters |
|
cubic centimeters |
cubic feet |
cubic inches |
cubic yards |
|
kilograms |
grams |
ounces |
pounds |
|
degrees Celsius |
degrees Fahrenheit |
degrees Kelvin |
A much 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", ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access