A conversion factor is a multiplier for changing a measurement from one unit to another. If 1 pound equals 16 ounces, the pound-to-ounce factor is 16: multiply 5 pounds by 16 to get 80 ounces. To go the other way, use the reciprocal, 1 ÷ 16. section 3.5.1
Storing a factor for every pair of units soon becomes awkward. With 20 length units, even storing just one direction for each pair requires 190 factors. A simpler approach chooses one standard unit per quantity, such as meters for length. Convert the input to that standard unit, then convert from the standard unit to the requested unit. section 3.5.1
Convert through a standard unit
Suppose kilograms are the standard unit for mass. The configuration records that 1 pound is 0.453592 kilograms and 1 gram is 0.001 kilograms. To convert pounds to grams, multiply the number of pounds by 0.453592, then divide by 0.001. In general: output value = input value × input unit’s standard-unit factor ÷ output unit’s standard-unit factor. section 3.6.2
def convert_value(
quantity_name: str,
from_unit_name: str,
to_unit_name: str,
value: float) -> Result:
quantity = unit_config[quantity_name]
from_unit = quantity.units[from_unit_name]
to_unit = quantity.units[to_unit_name]
# Two-step conversion: from-unit to standard unit, then to to-unit
value_in_to_units = (value *
from_unit.value_in_std_units /
to_unit.value_in_std_units)
return Result(from_unit, to_unit, value, value_in_to_units)
The backend function shows the two-step calculation in Python: it looks up both units’ factors, multiplies by the source factor, and divides by the destination factor. section 3.6.2
Keep quantities, units, and factors together in one configuration file rather than hard-coding them into the interface. The interface can offer the configured units, while the backend performs the conversion. This approach suits fixed factors; currency exchange rates change frequently and would need a source of current rates. section 3.5.2 section 3.3.1
