Units and Conversion
A measurement is a number and a unit: 5 is meaningless, 5 km is not. This lesson converts between units with conversion factors, chains several conversions, handles squared units and temperatures, and builds a small table-driven unit converter of the kind used in real software.
Conversion factors are fractions equal to 1
Since , the fraction equals 1. Multiplying by 1 does not change a quantity, only its unit. Choose the factor so the unit you want to get rid of cancels:
This method is called dimensional analysis (or the factor-label method). Writing the units out makes mistakes visible: if the units don't cancel, the factor is upside down.
Common conversions
| Quantity | Conversion |
|---|---|
| length | , , (exact), (exact) |
| mass | , (exact) |
| volume | , |
| time | , , |
| data | , , |
Chaining conversions
Convert 90 km/h to metres per second:
Each factor cancels one unit. And how many seconds are in a (non-leap) year? .
Squared and cubed units
A square metre is , so , not 100. Apply the factor once per dimension:
Temperature is different
Celsius and Fahrenheit have different zero points, so you cannot just multiply:
, , and −40 is the same in both scales. Kelvin is Celsius shifted: .
A table-driven converter
Real code stores factors to one base unit per quantity, then converts any unit to any other via the base. Decimal keeps the exact factors exact:
from decimal import Decimal as D
TO_METRES = {"mm": D("0.001"), "cm": D("0.01"), "m": D(1), "km": D(1000),
"in": D("0.0254"), "ft": D("0.3048"), "mi": D("1609.344")}
def convert(value, unit_from, unit_to):
metres = D(value) * TO_METRES[unit_from]
return metres / TO_METRES[unit_to]
print(convert("3.2", "km", "m"))
print(convert("12", "in", "cm"))
print(convert("26.2", "mi", "km")) # a marathon
print(convert("6", "ft", "m"))
print(convert("1", "km", "mi"))3200.0
30.48
42.1648128
1.8288
0.6213711922373339696174341844
1 km → miles has no finite decimal ( is not a fraction with only 2s and 5s in the denominator), so Decimal gives 28 significant digits; round it for display.
Currency
Exchange rates are conversion factors that change every minute, and the "unit" is a currency. Converting money must round to the target currency's smallest unit, and some currencies have no cents at all:
from decimal import Decimal, ROUND_HALF_EVEN
RATES_PER_USD = {"USD": Decimal("1"), "EUR": Decimal("0.9210"), "JPY": Decimal("151.37")}
MINOR = {"USD": Decimal("0.01"), "EUR": Decimal("0.01"), "JPY": Decimal("1")}
def fx(amount, src, dst):
usd = Decimal(amount) / RATES_PER_USD[src]
return (usd * RATES_PER_USD[dst]).quantize(MINOR[dst], rounding=ROUND_HALF_EVEN)
print(fx("250.00", "USD", "EUR"))
print(fx("250.00", "USD", "JPY"))
print(fx("100.00", "EUR", "JPY"))230.25
37842
16435
(The rates here are made up for the example.)
In software
- Unit bugs are expensive. A famous spacecraft was lost because one team's software used pound-force seconds and another's used newton seconds. Store values in one base unit (SI) internally and convert only at the edges (input and display).
- Units in names:
timeout_ms,size_bytes,distance_m. Some languages and libraries (F# units of measure, Python'spint) check units at compile or run time. - Data sizes: disks are sold in GB ( bytes) but operating systems often show GiB ( bytes), which is why a "1 TB" drive shows about 931 GiB. See Powers of Two.
- CSS: by definition, and
remconverts via the root font size.
Exercises
Exercise 1: One factor
Convert 7.5 kg to grams and 2400 mL to litres.
Answer
7500 g and 2.4 L
Solution
Exercise 2: Chain them
A runner keeps a pace of 5 minutes per kilometre. What is that speed in km/h and in m/s?
Answer
12 km/h, which is m/s (about 3.33 m/s).
Solution
Exercise 3: Area and temperature
Convert to , and 25 °C to °F.
Answer
and 77 °F
Solution
Exercise 4: The missing gibibytes
A drive is sold as 2 TB ( bytes). Write Python that shows its size in GiB ( bytes) and TiB ( bytes), rounded to 1 decimal place.
Answer
About 1862.6 GiB, or 1.8 TiB.
Solution
.
size = 2 * 10**12
print(f"{size / 2**30:.1f} GiB, {size / 2**40:.1f} TiB")1862.6 GiB, 1.8 TiB
Test yourself
How many are in ?
- 100
- 1000
- 10 000
- 1 000 000
To convert 54 km/h to m/s, multiply by…
- 60
What is 50 °F in °C?
- 10 °C
- 18 °C
- 122 °C
- −10 °C