Search for "km to miles" and you will see answers that differ in the third decimal. The reason is almost always a rounded conversion factor. Here is how to get consistent, defensible results in code.
Use the exact definitions
Several common units are defined exactly in terms of metric units:
- 1 inch = 25.4 millimetres (exact)
- 1 mile = 1.609344 kilometres (exact)
- 1 pound = 0.45359237 kilograms (exact)
- 1 US gallon = 3.785411784 litres (exact)
If you use 1.6 or 0.62 as shortcuts, errors grow with the size of the number: a 42.195 km marathon becomes 26.2 miles instead of 26.2188.
const KM_PER_MILE = 1.609344; const kmToMiles = (km) => km / KM_PER_MILE; console.log(kmToMiles(42.195)); // 26.2187... Convert through one base unit
If you support many units, store one factor per unit relative to a base unit (metres for length) and convert through it. That needs N factors instead of N times N pairs and removes a whole class of typos:
const LENGTH = { m: 1, km: 1000, mi: 1609.344, ft: 0.3048, in: 0.0254, yd: 0.9144 }; function convert(value, from, to) { return value * LENGTH[from] / LENGTH[to]; } console.log(convert(10, 'km', 'mi')); // 6.2137... Round for display only
Keep full precision while calculating and round once when showing the result. Rounding between steps compounds the error.
Temperature is different
Celsius, Fahrenheit and Kelvin need an offset as well as a scale, so a single multiplier does not work: F = C * 9/5 + 32.
Check against a reference
Test a few known pairs: 1 inch to 25.4 mm, 1 mile to 1.609344 km, 0 C to 32 F. If those pass, the rest follow.
A working converter
I keep a free set of unit converters, with the exact factors shown on each page, at https://unitconverter.network/ . Examples: https://unitconverter.network/km-to-miles/ and https://unitconverter.network/inches-to-mm/ .

