Total an invoice with tax

Python · Python · advanced · greenfield

Adds the invoice total: sums the line items, applies tax, and returns the total in whole cents using Decimal so there's no float error. Rounds half-up to the cent.

Line prices are stored as integer cents; tax_rate is a Decimal from the tax config. Invoices are ordinary retail scale — subtotals well under a few million cents — so every value fits the default Decimal context's 28 significant digits exactly.

Requirements

Files touched

--- app/billing/invoice.py
+from decimal import Decimal, ROUND_HALF_UP
+
+
+def invoice_total(line_items: list[tuple[int, int]], tax_rate: Decimal) -> int:
+    subtotal = sum(price * qty for price, qty in line_items)
+    taxed = Decimal(subtotal) * (Decimal(1) + tax_rate)
+    cents = taxed.quantize(Decimal(1), rounding=ROUND_HALF_UP)
+    return int(cents)

Review this PR

Python practice