DEV Community

Moarij0
Moarij0

Posted on

Build a Road Trip Fuel Cost Calculator in JavaScript

A road trip fuel calculator is one of the friendliest beginner projects: the maths is simple, but it teaches input validation, units and rounding.

The core formula

function tripFuelCost({ distanceKm, kmPerLitre, pricePerLitre, roundTrip = false }) {
  if (distanceKm <= 0 || kmPerLitre <= 0 || pricePerLitre <= 0) {
    throw new Error('All values must be positive');
  }
  const km = roundTrip ? distanceKm * 2 : distanceKm;
  const litres = km / kmPerLitre;
  return { litres: +litres.toFixed(1), cost: Math.round(litres * pricePerLitre) };
}

// Example values only
console.log(tripFuelCost({ distanceKm: 600, kmPerLitre: 12, pricePerLitre: 250, roundTrip: true }));
Enter fullscreen mode Exit fullscreen mode

Details that make it useful

  • Round trip toggle: most people forget the drive back
  • A safety margin: hills, traffic and AC lower your real average, so add 10 to 15 percent
  • Live fuel price: hard-coding the price makes the tool wrong after the next revision. Fetch it or let users edit it
  • Clear rounding: show litres to one decimal and money as whole numbers

Compare with a live tool

In Pakistan, fuel prices are revised regularly, so a real tool needs the current rate. BaKhabar Pakistan's trip planner does this kind of calculation, and its fuel prices page lists the latest petrol and diesel rates.

Try building the function, then add tests for zero and negative inputs. Small projects like this are a good way to practise writing code that real people can use.

Top comments (0)