If you have ever built a fuel log, you probably divided litres on a receipt by kilometres since the last receipt. That gives a number every time, and it is wrong most of the time. Here is the model that gives a number only when it can be right.
Rule 1: consumption exists only between two full fills
A tank you filled to the top is a known state. A partial fill is not. So an interval is:
- start: a confirmed full fill (odometer reading A)
- end: the next confirmed full fill (odometer reading B)
- fuel used: every litre added after the start fill, up to and including the end fill, partial fills included
- distance: B − A
function intervals(fills) { // fills sorted by odometer const out = []; let start = null, fuel = 0n; for (const f of fills) { if (start !== null) fuel += f.millilitres; if (f.full) { if (start !== null) out.push({ from: start.odo, to: f.odo, ml: fuel }); start = f; fuel = 0n; } } return { closed: out, open: start && fuel > 0n ? { from: start.odo, ml: fuel } : null }; } Anything after the last full fill is an open interval. Show it as open; do not estimate it.
Rule 2: store one base unit, convert exactly
Store fuel in millilitres and distance in metres as integers. The conversion constants are exact by definition:
- 1 US gallon = 3,785.411784 mL
- 1 Imperial gallon = 4,546.09 mL
- 1 mile = 1,609.344 m
Keep them as rationals (3785411784n / 1000000n) and convert at input and display time, rounding once, at the end.
Rule 3: reject what cannot be true
- odometer goes backwards → conflict, not a negative distance
- full fill with zero fuel added since the last one → ignore the interval
- one vehicle mixing litres and gallons → fine, if each fill carries its own unit
Why it matters
Trip profit depends on fuel cost per kilometre. A consumption figure from a single receipt can be off by a third, which is enough to turn a profitable quote into a loss.
This is the model behind Fleet Fuel & Trip Profit Control (paid, with a free demo).