Converting miles per gallon to kilometer per liter in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 17-Apr-2021 14:33:02
Advertisements