Emmanuel Akinfulubi

JavaScriptMath

Unit conversion round trips in JavaScript

Beginner · 4 min read

Running apps switch between kilometers and miles. Weather apps switch between Celsius and Fahrenheit. Shops switch between kilograms and pounds. Unit conversion looks like the simplest code there is, one multiplication, but two things go wrong in practice: people use rough factors, and converting there and back doesn't always give back the number you started with.

In this tutorial you will convert kilometers to miles, Celsius to Fahrenheit and kilograms to pounds using their exact official factors. Then you will convert back and count which values come home unchanged. You will also find the one temperature that reads the same on both scales. You need to know arrow functions and for loops.

Exact factors

A mile is exactly 1.609344 km and a pound is exactly 0.45359237 kg. These are not measurements. They are definitions, agreed between countries in 1959. So rough values like 1.6 or 2.2 are not "close enough versions" of anything; they are simply different numbers. Writing the exact factor costs nothing.

Temperatures

Celsius and Fahrenheit differ in two ways: the size of a degree and where zero sits. Going out multiplies by 9/5 and adds 32. Coming back undoes it in the opposite order:

Output

F = C * 9 / 5 + 32
C = (F - 32) * 5 / 9

Kelvin is simpler: it is Celsius plus 273.15.

Here is the exercise. Try it on your own first if you like, then read on and we will build it together.

99 Unit conversion, and which round trips survive

easy

Convert kilometres to miles, Celsius to Fahrenheit and kilograms to pounds, each with its exact defined factor. Then convert back and count how many values come home unchanged. Find the temperature that is the same on both scales.

Stuck? Three hints, smallest first
  1. 1. A mile is exactly 1.609344 km and a pound is exactly 0.45359237 kg. Both are definitions.
  2. 2. c * 9 / 5 + 32 going out, (f - 32) * 5 / 9 coming back.
  3. 3. Dividing and then multiplying by the same factor is two roundings, and they do not always cancel.

Step 1: distance

Step 1

const MILE_IN_KM = 1.609344;
const kmToMiles = (km) => km / MILE_IN_KM;
const milesToKm = (mi) => mi * MILE_IN_KM;
console.log(milesToKm(1));       // 1.609344
console.log(kmToMiles(100));     // 62.13711922373339
console.log(kmToMiles(42.195));  // 26.218757456454306

A mile is exactly the factor, and a marathon (42.195 km) is about 26.22 miles. Constants in capital letters, like MILE_IN_KM, are a common way to mark a fixed value.

Step 2: the round trip

Now convert to miles and straight back.

Step 2

console.log(milesToKm(kmToMiles(100)));    // 100
console.log(milesToKm(kmToMiles(42.195))); // 42.195
console.log(milesToKm(kmToMiles(7)));      // 6.999999999999999

100 and 42.195 come back exactly. 7 comes back as 6.999999999999999.

Why? JavaScript stores numbers in binary, and most results of a division can't be stored exactly. So 7 / 1.609344 is rounded to the nearest number the computer can hold. Then multiplying back is rounded again. Sometimes the two roundings cancel out, sometimes they don't, and there is no simple way to tell in advance.

Step 3: temperatures

Step 3

const cToF = (c) => (c * 9) / 5 + 32;
const fToC = (f) => ((f - 32) * 5) / 9;
console.log(cToF(37), fToC(98.6)); // 98.6 37
console.log(cToF(-40));            // -40

Body temperature converts cleanly both ways. And -40 is the one temperature that is the same on both scales: -40 * 9 / 5 is -72, plus 32 is -40.

Step 4: count the failures

Step 4

console.log(fToC(cToF(0.1))); // 0.09999999999999984
const failingCelsius = (lo, hi) => {
  const out = [];
  for (let c = lo; c <= hi; c++) if (fToC(cToF(c)) !== c) out.push(c);
  return out;
};
console.log(failingCelsius(-50, 50).length);      // 18
console.log(failingCelsius(-50, 50).slice(0, 5)); // [ -7, -3, -2, -1, 1 ]

0.1 °C comes back as 0.09999999999999984. Of the 101 whole-number temperatures from -50 to 50, 18 don't survive the trip. -7 comes back as -7.000000000000001. There is no pattern you could guess.

The wrong turn here is testing conversions with ===. In a test suite, compare with a small tolerance, or round to the precision that matters (one decimal place for a thermometer).

Step 5: Kelvin is safer

Step 5

const cToK = (c) => c + 273.15;
const kToC = (k) => k - 273.15;
console.log(kToC(cToK(25)), kToC(cToK(25)) === 25); // 25 true

Kelvin is only an offset: add, then subtract the same number. That undoes itself far more reliably than multiplying and dividing. It is not a guarantee for every value, but 25 comes back exactly.

Step 6: weight

Step 6

const POUND_IN_KG = 0.45359237;
const kgToPounds = (kg) => kg / POUND_IN_KG;
console.log(kgToPounds(70));                     // 154.3235835294143
console.log(Number(kgToPounds(70).toFixed(2)));  // 154.32

70 kg is about 154.32 pounds. toFixed(2) rounds to two decimal places and returns text, and Number turns it back into a number. Rounding to a sensible precision like this is what you would show a user.

The full solution

The answer panel has every converter and failingCelsius, and prints the mile, the 100 km, 7 km and marathon round trips, the temperatures, the 18 failures, the Kelvin round trip and 70 kg in pounds. Press Run to see the output.

The answer

const MILE_IN_KM = 1.609344;         // exact, by international agreement
const POUND_IN_KG = 0.45359237;      // also exact

const kmToMiles = (km) => km / MILE_IN_KM;
const milesToKm = (mi) => mi * MILE_IN_KM;
const kgToPounds = (kg) => kg / POUND_IN_KG;
const cToF = (c) => (c * 9) / 5 + 32;
const fToC = (f) => ((f - 32) * 5) / 9;
const cToK = (c) => c + 273.15;
const kToC = (k) => k - 273.15;

const failingCelsius = (lo, hi) => {
  const out = [];
  for (let c = lo; c <= hi; c++) if (fToC(cToF(c)) !== c) out.push(c);
  return out;
};

console.log('one mile          :', milesToKm(1), 'km, exactly');
console.log('100 km            :', kmToMiles(100), 'miles, back to', milesToKm(kmToMiles(100)));
console.log('7 km              :', kmToMiles(7), 'miles, back to', milesToKm(kmToMiles(7)));
console.log('a marathon        :', kmToMiles(42.195), 'miles');
console.log('body temperature  :', cToF(37), 'F, and back', fToC(98.6));
console.log('the crossing point:', cToF(-40));
console.log('0.1 C out and back:', fToC(cToF(0.1)));
console.log('integer C failures:', failingCelsius(-50, 50));
console.log('kelvin round trip :', kToC(cToK(25)), kToC(cToK(25)) === 25);
console.log('70 kg             :', kgToPounds(70), 'pounds');

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a mile is exactly 1.609344 km, because that is how a mile is defined', [milesToKm(1), milesToKm(1) === MILE_IN_KM], [1.609344, true]);
test('100 km is 62.13711922373339 miles, and that value does round trip', [kmToMiles(100), milesToKm(kmToMiles(100)) === 100], [62.13711922373339, true]);
test('7 km does not: it comes back as 6.999999999999999', [milesToKm(kmToMiles(7)), milesToKm(kmToMiles(7)) === 7], [6.999999999999999, false]);
test('a marathon is 26.218757456454306 miles, and that one survives the trip', [kmToMiles(42.195), milesToKm(kmToMiles(42.195)) === 42.195], [26.218757456454306, true]);
test('the two temperature scales cross at -40, and exactly there', [cToF(-40), cToF(-40) === -40], [-40, true]);
test('37 Celsius is 98.6 Fahrenheit and 98.6 is 37, both exactly', [cToF(37), fToC(98.6)], [98.6, 37]);
test('but 0.1 Celsius comes home as 0.09999999999999984', [fToC(cToF(0.1)), fToC(cToF(0.1)) === 0.1], [0.09999999999999984, false]);
test('18 of the 101 integer Celsius values from -50 to 50 fail the round trip', [failingCelsius(-50, 50).length, failingCelsius(-50, 50).slice(0, 5)], [18, [-7, -3, -2, -1, 1]]);
test('kelvin is a pure offset so it round trips, and 70 kg is 154.32 pounds', [kToC(cToK(25)) === 25, Number(kgToPounds(70).toFixed(2))], [true, 154.32]);

Use the defined factors. A mile is exactly 1.609344 km and a pound is exactly 0.45359237 kg — those are definitions agreed in 1959, not measurements, so 1.6 and 2.2 are not approximations of anything, they are just wrong. Writing the exact value costs nothing and removes a whole class of "why is my total off by 60 metres" question.

Even with exact factors, a conversion followed by its inverse is two roundings and they do not always cancel. 100 km and a full marathon both come home unchanged; 7 km comes back as 6.999999999999999. Eighteen of the 101 integer Celsius values between -50 and 50 fail the same way, and 0.1 C returns as 0.09999999999999984. There is no pattern you can reason about in advance — which is why a unit-conversion test suite should compare with a tolerance, or round to the precision the domain actually uses, and never with ===.

Two nice edges. -40 is the fixed point of the Celsius-Fahrenheit pair, and it lands exactly, because -40 * 9 / 5 is exact and so is the rest. And Kelvin is a pure offset rather than a scaling, so c + 273.15 - 273.15 returns the original: addition and subtraction of the same constant undo each other far more reliably than multiplication and division do.

Common mistakes

  • Using rough factors. 1.6 km per mile is wrong by about 9 meters a mile. Use 1.609344.
  • Testing round trips with ===. Two roundings don't always cancel. Compare with a tolerance or round first.
  • Getting the temperature order wrong. Coming back, subtract 32 before multiplying by 5/9.

Try it yourself

  1. Write poundsToKg and check whether 70 kg survives the trip to pounds and back.
  2. Write closeEnough(a, b) that allows a difference of 1e-9, and use it to count Celsius failures from -50 to 50 again.
  3. Convert 10 km to miles with 1.6 instead of 1.609344. How far off is the answer, in meters?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.