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
- invoice_total(line_items, tax_rate) returns the total in cents.
- Each line item is (unit_price_cents: int, quantity: int); tax_rate is a Decimal like Decimal('0.21').
- Money must be exact — no floating-point rounding error — and the total rounds to a whole cent.
Files touched
- app/billing/invoice.py
--- 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)