Converting miles per gallon to kilometer per liter in JavaScript


Problem

We are required to write a JavaScript function that takes in a number in miles/gallon and return its equivalent km/litre.

Example

Following is the code −

 Live Demo

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));

Output

Following is the console output −

8.85

Updated on: 17-Apr-2021

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements