Emmanuel Akinfulubi

JavaScriptBasic

Convert kilometers to miles in JavaScript

Beginner · 3 min read

Kilometers and miles both measure distance. Running apps, maps, travel sites and car dashboards often need to show both, so converting between them is a small job that turns up everywhere.

In this tutorial you will write toMiles and toKm, keep the conversion number in one named constant, and see how much a rounded "about 1.6" gets wrong. You need to know what a function is and how to multiply and divide in JavaScript.

The conversion factor

One mile is exactly 1.609344 kilometers. That is not a measurement that might be slightly off: since 1959, the mile has been defined as 1,609.344 meters by international agreement. So the number is exact, and any error in your result comes from your code, not from the factor.

To go between the two:

  • kilometers to miles: divide by 1.609344 (a mile is longer, so there are fewer of them)
  • miles to kilometers: multiply by 1.609344

Why a named constant

If 1.609344 is typed in several places, sooner or later one of them gets typed as 1.609 or 1.6, or someone uses 0.621 for one direction and 1.609 for the other. Those two numbers are not exact opposites, so a distance converted out and back no longer matches. Writing the factor once, as a constant, means every conversion uses the same value.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

69 Kilometres and miles

easy

Convert kilometres to miles and back. Keep the conversion factor in one place, and say what the exact factor is.

Stuck? Three hints, smallest first
  1. 1. One mile is exactly 1.609344 kilometres, by international agreement since 1959.
  2. 2. Divide to go from kilometres to miles, multiply to come back.
  3. 3. Store the factor as a named constant; a magic 1.6 sprinkled through code is how conversions drift.

Step 1: one constant, two functions

Step 1

const KM_PER_MILE = 1.609344; // exact, by definition
const toMiles = (km) => km / KM_PER_MILE;
const toKm = (miles) => miles * KM_PER_MILE;
console.log(toMiles(100)); // 62.13711922373339
console.log(toKm(26.2));   // 42.1648128

The constant is written in capitals, a common way to say "this value never changes". The name says what it is: kilometers per mile. Both functions use it, so they are always exact opposites of each other.

100 km is a little over 62 miles. A marathon, 26.2 miles, is about 42.16 km.

Step 2: round for display

Nobody wants fourteen decimal places on a map. Round to two, and keep the result a number:

Step 2

const KM_PER_MILE = 1.609344;
const toMiles = (km) => km / KM_PER_MILE;
const round2 = (n) => Number(n.toFixed(2));
console.log(round2(toMiles(100))); // 62.14
console.log(round2(toMiles(128))); // 79.54

toFixed(2) rounds to two decimal places but gives back text. Number(...) turns it back into a number. 128 km, about the road distance from Lagos to Ibadan, is 79.54 miles.

Round only when you show the value. If you round in the middle of a calculation, the rounding error is carried into everything after it.

Step 3: check the round trip

Converting out and back should give you the value you started with:

Step 3

const KM_PER_MILE = 1.609344;
const toMiles = (km) => km / KM_PER_MILE;
const toKm = (miles) => miles * KM_PER_MILE;
console.log(toMiles(KM_PER_MILE));  // 1
console.log(toKm(toMiles(100)));    // 100
console.log(toMiles(0), toKm(0));   // 0 0

One mile's worth of kilometers is one mile, and 100 km comes back as exactly 100. That works here, but decimals are stored in binary and some values may come back a tiny bit off. When you compare converted numbers, a tolerance (as in the floating-point comparison lesson) is safer than ===.

Step 4: what "about 1.6" costs

1.6 is a handy number for mental math. In code it is a bug:

Step 4

const KM_PER_MILE = 1.609344;
const toMiles = (km) => km / KM_PER_MILE;
const round2 = (n) => Number(n.toFixed(2));
console.log(round2(100 / 1.6));                    // 62.5
console.log(round2(1000 / 1.6 - toMiles(1000)));   // 3.63

At 100 km, 1.6 gives 62.5 miles instead of 62.14. At 1,000 km the gap is 3.63 miles. The rough factor is wrong by the same share every time, so the error grows with the distance.

The full solution

The answer panel has the constant and both functions, prints 100 km, Lagos to Ibadan and a marathon, and the result of using 1.6. Its checks cover the round trip, zero, and how the 1.6 error grows. Press Run to see the output.

The answer

const KM_PER_MILE = 1.609344;          // exact, by definition

const toMiles = (km) => km / KM_PER_MILE;
const toKm = (miles) => miles * KM_PER_MILE;

const round2 = (n) => Number(n.toFixed(2));

console.log('100 km ->', round2(toMiles(100)), 'miles');
console.log('Lagos to Ibadan, 128 km ->', round2(toMiles(128)), 'miles');
console.log('a marathon, 26.2 miles ->', round2(toKm(26.2)), 'km');
console.log('rough factor 1.6 would say', round2(100 / 1.6), 'miles');

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a hundred kilometres in miles', round2(toMiles(100)), 62.14);
test('Lagos to Ibadan', round2(toMiles(128)), 79.54);
test('a marathon in kilometres', round2(toKm(26.2)), 42.16);
test('one mile of kilometres is one mile', toMiles(KM_PER_MILE), 1);
test('the round trip returns the value here', toKm(toMiles(100)), 100);
test('zero is zero in both units', [toMiles(0), toKm(0)], [0, 0]);
test('the rough 1.6 factor gives a different answer', round2(100 / 1.6) !== round2(toMiles(100)), true);
test('and the error grows with distance', round2(1000 / 1.6 - toMiles(1000)), 3.63);

The factor is exact — a mile is defined as 1609.344 metres — so any error here is yours, not the arithmetic's. Rounding it to 1.6 is out by 0.58%, and that error scales: about a third of a mile over 100km, three and a half miles over 1,000.

One named constant, used by both directions, is the point. Two hand-written factors (1.609 for one way, 0.621 for the other) drift apart and stop being inverses, so a value converted out and back no longer matches what was stored. The round trip is exact for 100 here, but do not lean on that in general — exercise 62's tolerance is the safe way to compare converted floats.

Common mistakes

  • Multiplying when you should divide. Kilometers to miles is a division. If 100 km comes out as 160 miles, you went the wrong way.
  • Using two different factors. 0.621 and 1.609 are not exact opposites. Use one constant for both directions.
  • Rounding in the middle. Round once, when you display the number.

Try it yourself

  1. Convert a 5 km run and a 10 km run to miles, rounded to two decimal places.
  2. Write formatDistance(km, unit) that returns text like '62.14 mi' or '100 km'.
  3. Add toMeters(miles) using the fact that one mile is 1,609.344 meters, and check it against toKm(miles) * 1000.

Keep practising

Newsletter

New writing, when it lands.

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