Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Converting miles per gallon to kilometer per liter in JavaScript
Converting miles per gallon (MPG) to kilometers per liter (km/L) is a common unit conversion in JavaScript applications dealing with fuel efficiency across different measurement systems.
Understanding the Conversion
To convert MPG to km/L, we need two conversion factors:
- 1 mile = 1.609344 kilometers
- 1 gallon = 4.54609188 liters (Imperial gallon)
The conversion formula is: km/L = MPG × (1.609344 ÷ 4.54609188)
Example Implementation
const num = 25;
const converter = (mpg) => {
let LITRES_PER_GALLON = 4.54609188;
let KILOMETERS_PER_MILE = 1.609344;
const ratio = KILOMETERS_PER_MILE / LITRES_PER_GALLON;
return Math.round(100 * mpg * ratio) / 100;
};
console.log(converter(num));
8.85
Enhanced Version with Validation
Here's an improved version with input validation and better readability:
function mpgToKmL(mpg) {
// Input validation
if (typeof mpg !== 'number' || mpg <= 0) {
throw new Error('Input must be a positive number');
}
const LITERS_PER_GALLON = 4.54609188;
const KILOMETERS_PER_MILE = 1.609344;
const conversionRatio = KILOMETERS_PER_MILE / LITERS_PER_GALLON;
// Round to 2 decimal places
return Math.round(mpg * conversionRatio * 100) / 100;
}
// Test with different values
console.log(`25 MPG = ${mpgToKmL(25)} km/L`);
console.log(`30 MPG = ${mpgToKmL(30)} km/L`);
console.log(`40 MPG = ${mpgToKmL(40)} km/L`);
25 MPG = 8.85 km/L 30 MPG = 10.62 km/L 40 MPG = 14.16 km/L
How It Works
The conversion process involves three steps:
- Calculate the conversion ratio:
1.609344 ÷ 4.54609188 ? 0.354 - Multiply the MPG value by this ratio
- Round the result to 2 decimal places using
Math.round()
US vs Imperial Gallons
Note that this example uses Imperial gallons (4.546 L). For US gallons (3.785 L), use this version:
function mpgToKmLUS(mpg) {
const LITERS_PER_US_GALLON = 3.78541178;
const KILOMETERS_PER_MILE = 1.609344;
const conversionRatio = KILOMETERS_PER_MILE / LITERS_PER_US_GALLON;
return Math.round(mpg * conversionRatio * 100) / 100;
}
console.log(`25 MPG (US) = ${mpgToKmLUS(25)} km/L`);
25 MPG (US) = 10.62 km/L
Conclusion
Converting MPG to km/L requires understanding the conversion ratios between miles/kilometers and gallons/liters. The key is applying the correct gallon measurement (Imperial vs US) for accurate results.
