Unit converters look simple, but a few details decide whether the numbers look right to users.
Use one base unit
Convert everything to a base unit first (metres for length, grams for mass), then out to the target. This needs only one factor per unit instead of a table of every pair.
const toMetre = { mm: 0.001, cm: 0.01, m: 1, km: 1000, in: 0.0254, ft: 0.3048, yd: 0.9144, mi: 1609.344 };
function convert(value, from, to) {
return value * toMetre[from] / toMetre[to];
}
The inch is defined as exactly 25.4 mm, so 0.0254 is exact and not a rounded value.
Floating-point output
In JavaScript, 0.1 + 0.2 gives 0.30000000000000004. For display, round at the end, not during the calculation:
const show = (n, digits = 6) => Number(n.toPrecision(digits)).toString();
show(convert(25, 'mm', 'in')); // 0.984252
Temperature is different
Temperature needs an offset as well as a factor, so keep it as its own function and do not put it in the table.
const cToF = c => c * 9 / 5 + 32;
Useful extras
- Let users swap the two units with one click.
- Show the formula so people can check it by hand.
- Accept decimals and negative numbers where they make sense.
If you want to compare your results against a ready-made tool, my unit converter covers length, weight, temperature and more.
Top comments (0)