5.15. Converting Between Units of Measurement

Problem

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

Solution

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

Discussion

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 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.