To the Top

MPG Calculator with API (Miles Per Gallon, Kilometres per litre, Litres per 100km)

Buy Me A Coffee

MPG (Miles Per Gallon) is a useful indicator of how fuel-efficiency of your car. The higher MPG, the better fuel efficiency. For urban, roughly the MPG is ranged from 20 to 40 while on rural, the MPG can go above 50. The MPG depends on many factors:

You can get an estimation of your fuel-spending of your current car by entering the Miles (Distances) and the Litres since your last fill-up.

  • MPG: 22.73
  • Litres Per 100km: 12.427454732996
  • km Per Litre: 8.0467
Miles (1 Mile = 1.60934 km): Litres (1 Litre = 0.219969 Imperial Gallon):

MPG Calculator Application Programming Interface (API)

We provide a simple API (subject to fair use policy) that computes the Miles Per Gallon, Kilometres per litre and Litres per 100km.

API example:
  https://helloacm.com/api/mpg-calculator/?cached&miles=100&litres=20
returns: 
  {"mpg":22.73,"litres_per_100km":12.427454732996,"km_per_litre":8.0467}

You can call the MPG Calculator via the POST method, for example:

? curl -s -X POST https://helloacm.com/api/mpg-calculator/ -d "miles=100" -d "litres=20"
{"mpg":22.73,"litres_per_100km":12.427454732996,"km_per_litre":8.0467}

If you are using POST method, the result will not be cached via the CloudFlare CDN, as the GET method does (via ?cached URL).

MPG Calculator API Servers

You can use one of the following API calling servers.

  1. Load Balancer: https://api.justyy.workers.dev/api/

API Core Source Code of MPG Calculator in PHP

// https://helloacm.com/tools/mpg-calculator/
  $miles = $_GET['miles'] ?? ($_POST['miles'] ?? 0);
  $litres = $_GET['litres'] ?? ($_POST['litres'] ?? 0);
  
  $miles = (float)$miles;
  $litres = (float)$litres;  
  
  if (($miles == 0) || ($litres == 0)) {
    $data = array(
      "error" => "check inputs"
    );
  } else {
    // Miles per Gallon
    $mpg = $miles / ($litres / 4.546);
    
    // Litres per 100km    
    $per100km = $litres / (($miles * 1.60934) * 0.01);
    
    // Kilometres per litre
    $kmperlitre = $miles * 1.60934 / $litres;
    
    $data = array(
      "mpg" => $mpg,
      "litres_per_100km" => $per100km,
      "km_per_litre" => $kmperlitre  
    );
  }

  header("Access-Control-Allow-Origin: *");
  header('Content-Type: application/json');
  die(json_encode($data));

API Servers to Compute the MPG

You can use one of the following API calling servers subject to fair-use policy.

  1. Load Balancer: https://api.justyy.workers.dev/api/

Other Versions

MPG油耗计算器

Share: List of Many Other Online Tools