- Instant help with your JavaScript coding problems

Convert kilometers to miles in JavaScript

Question:
How to convert kilometers to miles in JavaScript?
Answer:
function kmToMi(km) {
  return km * 0.621371;
}

console.log(kmToMi(54)); // 33.554034
Description:

Converting the distance from kilometers to miles is simple if you know the conversion rate. You can find it for example on Wikipedia.
Note that there are also nautical miles, which are not the same as statute miles. 

  • 1 mile = 1 609,344m
  • 1 nautical mile = 1852m

According to this, the conversion rates from km to mi are the following:

  • 1 km = 1000 / 1609,344 = 0.621371 statute mile
  • 1 km = 1000 / 1852 = 0.539957 nautical mile

So an essential JavaScript function that performs the conversion looks like this:

function kmToMi(km) {
  return km * 0.621371;
}

However, if you execute the function with an invalid value then your code will return with a NaN result. Depending on your needs you can handle this behavior with a code like this:

function kmToMi(km) {
    if (typeof km !== 'number') {
        return 'Error: invalid input value';
    }
    return km * 0.621371;
}

Another aspect is that in most cases you don't need a high-precision result, so 1-2 decimal places may be enough. By introducing an extra parameter you can further improve the code.

function kmToMi(km, precision = 2) {
    if (typeof km !== 'number') {
        return 'Error: invalid input value';
    }
    if (typeof precision !== 'number') {
        return 'Error: invalid precision value';
    }
    return Math.round(km * 0.621371 * Math.pow(10, precision)) / Math.pow(10, precision);
}

Finally, you can use it in TypeScript as follows:

function kmToMi(km: number, precision = 2) : number|string {
    if (typeof km !== 'number') {
        return 'Error: invalid input value';
    }
    if (typeof precision !== 'number') {
        return 'Error: invalid precision value';
    }
    return Math.round(km * 0.621371 * Math.pow(10, precision)) / Math.pow(10, precision);
}
Share "How to convert kilometers to miles in JavaScript?"