Convert kilometers to miles in JavaScript
function kmToMi(km) {
return km * 0.621371;
}
console.log(kmToMi(54)); // 33.554034
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);
}
- Convert Fahrenheit to Celsius in JavaScript
- Convert kilometers to miles in JavaScript
- Convert Map values to array in JavaScript
- Round a number to 2 decimal places in JavaScript
- Convert string to int in JavaScript
- Convert string to kebab case in JavaScript
- Convert snake case to camel case in JavaScript
- Capitalize words in a string using JavaScript
- Convert string to character array in JavaScript
- Convert camel case to snake case in JavaScript
- Remove accents from a string in JavaScript
- Convert a string to sentence case in JavaScript
- Convert string to title case in JavaScript
- Convert string to snake case in JavaScript
- Convert string to pascal case in JavaScript
- Convert string to camel case in JavaScript
- Convert string to uppercase with JavaScript
- Convert a float number to integer in JavaScript
- Convert object to JSON string in JavaScript
- Parse JSON string in JavaScript
- convert number to string in JavaScript