O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required