DEV Community

Tidy Cents
Tidy Cents

Posted on

Recipe cost per serving with yield and exact unit conversion in Python

Most recipe cost sheets divide the pack price by the amount used. That skips the yield: you pay for the whole onion, the plate only gets the peeled part. If 88% of a bag is usable, every gram on the plate costs 1/0.88 of a gram on the receipt.

Two more details make the number trustworthy:

  • Unit conversion inside one dimension is exact. A pound is defined as 0.45359237 kg, so a Fraction keeps it exact. No rounding until you print.
  • Weight to volume has no exact table. Density depends on your ingredient, so measure it once (how much of the pack unit one recipe unit really is) and pass that factor in.
from fractions import Fraction as F
# exact unit factors (NIST): grams per unit
G = {"g": F(1), "kg": F(1000), "lb": F(45359237, 100000), "oz": F(45359237, 1600000)}

def line_cost(pack_size, pack_unit, pack_price, yield_pct, qty, unit):
    """Cost of one recipe line, counted from what reaches the plate."""
    per_gram = F(pack_price) / (pack_size * G[pack_unit])
    per_gram_edible = per_gram / (F(yield_pct) / 100)
    return per_gram_edible * qty * G[unit]

batch = (line_cost(5, "kg", "4.50", 88, 400, "g")     # onion, 88% after peeling
       + line_cost(1, "lb", "3.60", 100, 50, "g")     # butter
       + F("1.20") * F("0.006") * 8)                   # salt: own measured factor, 8 tsp
serving = batch / 4 + F("0.25")                        # 4 servings + plate extras
print(f"batch {float(batch):.6f}  serving {float(serving):.6f}")
print(f"price at 30% food cost: {float(serving / F('0.30')):.2f}")
print(f"price with $5.50 left per plate: {float(serving + F('5.50')):.2f}")
print(f"food cost at $4.50: {float(serving / F('4.50') * 100):.4f}%")
print(f"30% margin: {float(serving / F('0.70')):.2f}  30% markup: {float(serving * F('1.30')):.2f}")
Enter fullscreen mode Exit fullscreen mode

Output:

batch 0.863523  serving 0.465881
price at 30% food cost: 1.55
price with $5.50 left per plate: 5.97
food cost at $4.50: 10.3529%
30% margin: 0.67  30% markup: 0.61
Enter fullscreen mode Exit fullscreen mode

Things worth noticing:

  • Counted from the receipt, the 400 g of onion costs $0.36. Counted from what reaches the plate, $0.41. On a whole menu that difference is real money.
  • The "plate extras" (bread, garnish, a container) are added per serving, after dividing the batch.
  • A food-cost target and a cash-per-plate target are two different pricing rules. Show both instead of picking one silently.
  • A 30% margin and a 30% markup are different prices ($0.67 vs $0.61 here). Name which one you mean in the code.

Free browser version with up to six ingredients: Recipe Cost Calculator (no sign-up).

Top comments (0)