5.15. Converting Between Units of Measurement


You want to convert between Fahrenheit and Centigrade, pounds and kilograms, or other units of measurement.


Write a custom method to perform the conversion and add it to the Math class.


There are various systems of measurement used throughout the world. For example, temperature is commonly measured with both the Fahrenheit and Centigrade scales, and weight is commonly measured using both pounds and kilograms. For these reasons, you may need to convert from one unit of measurement to another.

Each of these conversions has its own algorithm. For example, to convert from Centigrade to Fahrenheit, you should multiply by 9/5 and then add 32 (to convert from Fahrenheit to Centigrade, subtract 32 and multiply by 5/9). Likewise, you can multiply by 2.2 to convert pounds to kilograms, and you can divide by 2.2 to convert kilograms to pounds. We also saw in Recipe 5.12 how to convert angles from degrees to radians and vice versa.

Here is a temperature converter. The method takes three parameters: the name of the units from which you are converting, the name of the units to which you are converting, and the value to convert. In this example code, we define conversions between Fahrenheit and Centigrade (“F” is interpreted to mean “Fahrenheit”; “C” and “Celsius” are recognized alternatives to “Centigrade”):

Math.convertTemperature = function (fMeasure, tMeasure, val) { // Convert all names to lowercase to match any capitalization. ...

Get Actionscript Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.