Product case study · November 16, 2026

Give Claude Code a rounding rule before it fixes your invoice

Repair a small Python invoice calculator with Claude Code. Specify line-level rounding, preserve decimal inputs, and verify the result with fixed tests.

Reading time
6 min
Checked
Nov 16, 2026
Paper receipt strips pass through ochre inspection gates before collecting in a muted blue total tray
Decide where each fraction of a cent goes before adding the total.
Bottom line

Decimal arithmetic preserves the input, but only an explicit rounding policy tells the agent which total is correct.

Two lines priced at 0.005 each can produce a total of 0.02 or 0.01. Round each line to cents before adding and you get the first result. Add the exact amounts before rounding and you get the second. Switching to a decimal library does not choose between them.

That is the problem in this Claude Code lab. You will give the agent a small broken calculator, a written rule, and tests whose expected totals it must preserve. The useful output is a repair you can explain, including why rounding belongs inside the loop.

You need Bash on macOS, Linux or WSL, Python 3, and an installed, signed-in Claude Code. All amounts are fictional. The Python baseline and reference repair were checked locally; the Claude prompt is an authored exercise, not a recorded agent run. Official sources were checked November 16, 2026.

Reproduce the missing cent

Create a fresh practice folder:

rounding_lab=$(mktemp -d /tmp/claude-rounding.XXXXXX)
cd "$rounding_lab"
cat > invoice.py <<'PY'
def invoice_total(lines):
    total = sum(float(price) * quantity for price, quantity in lines)
    return f"{total:.2f}"
PY
python3 - <<'PY'
from invoice import invoice_total
print(invoice_total([("2.675", 1)]))
print(invoice_total([("0.005", 1), ("0.005", 1)]))
PY

The baseline prints 2.67 and 0.01. For our chosen rule, both should be one cent higher. They need different explanations: the first exposes a binary floating-point approximation; the second exposes when rounding happens.

Python’s Decimal documentation explains that constructing a decimal from a float preserves that float’s exact value, including its approximation. Build from the original price string instead. Its quantize method lets you specify a decimal exponent and rounding mode.

Choose the policy yourself

Save this contract as SPEC.md:

invoice_total(lines) receives a list of (unit_price, quantity) pairs.
This practice fixture supplies valid inputs only:
- At most 1,000 lines.
- unit_price is an unsigned decimal string from 0.000 to 9999.999,
  with at most three fractional digits and no exponent notation.
- quantity is an integer from 1 to 1,000.

For each line, multiply the exact decimal price by quantity.
Round that line amount to two decimal places using ROUND_HALF_UP.
Sum the rounded line amounts. Return a string with exactly two decimals.
An empty list returns "0.00".
Use a private decimal context with precision 28 so caller context changes
cannot silently alter the arithmetic. Do not change the caller's context.
Use only the Python standard library. Do not modify the input list.
Input validation, tax, discounts, refunds and currency conversion are
outside this exercise. Do not invent rules for them.

This is a software exercise with an intentionally chosen rule, not a claim about how every invoice should work. In a real project, get the required policy from the system owner before encoding it. A test cannot settle a business requirement nobody has specified.

Our quantity rule matters too. A line containing three units at 0.005 is rounded once after multiplication: 0.015 becomes 0.02. It is not three separately rounded units totaling 0.03.

Freeze the evidence before asking for a fix

Save the following as test_invoice.py:

import unittest
from decimal import ROUND_DOWN, localcontext
from invoice import invoice_total


class InvoiceTests(unittest.TestCase):
    def test_decimal_tie(self):
        self.assertEqual(invoice_total([("2.675", 1)]), "2.68")

    def test_round_each_line(self):
        self.assertEqual(
            invoice_total([("0.005", 1), ("0.005", 1)]), "0.02"
        )

    def test_multiply_before_rounding(self):
        self.assertEqual(invoice_total([("0.005", 3)]), "0.02")

    def test_ordinary_total_and_input_unchanged(self):
        lines = [("1.20", 2), ("0.10", 3)]
        before = lines.copy()
        self.assertEqual(invoice_total(lines), "2.70")
        self.assertEqual(lines, before)

    def test_empty(self):
        self.assertEqual(invoice_total([]), "0.00")

    def test_private_context_and_upper_bound(self):
        with localcontext() as caller:
            caller.prec = 6
            caller.rounding = ROUND_DOWN
            lines = [("9999.999", 1000)] * 1000
            self.assertEqual(invoice_total(lines), "9999999000.00")
            self.assertEqual(caller.prec, 6)
            self.assertEqual(caller.rounding, ROUND_DOWN)

Run the baseline before launching the agent:

python3 -m unittest -v test_invoice

The local baseline failed three of these six methods: the decimal tie, separate-line rounding, and multiplication-before-rounding cases. Keep that failure output. It identifies the bug more precisely than “the calculator is off by a cent.” Python’s unittest reference documents running a named test module and comparing exact results with assertEqual.

Start claude in the practice folder and paste:

Read SPEC.md, invoice.py and test_invoice.py.
Run python3 -m unittest -v test_invoice and report the baseline failures.
Explain the difference between input representation and rounding policy.
Change only invoice.py to satisfy the written contract.
Keep the tests and their expected values unchanged. Install no packages.
Run the same command again and report its actual result.
Explain why two separate 0.005 lines differ from one line of quantity 2.
Do not commit, delegate, or add features beyond SPEC.md.

Anthropic’s common workflows describes using reproducible errors and tests to guide debugging. Review the tool permissions Claude requests for this folder. The prompt describes the task boundary; it does not create a filesystem sandbox.

Inspect the rounding boundary

Here is a reference repair to compare with the agent’s proposal:

from decimal import Context, Decimal, ROUND_HALF_UP, localcontext


def invoice_total(lines):
    with localcontext(Context(prec=28)):
        cent = Decimal("0.01")
        total = Decimal("0.00")
        for price, quantity in lines:
            line = Decimal(price) * quantity
            total += line.quantize(cent, rounding=ROUND_HALF_UP)
        return f"{total:.2f}"

ROUND_HALF_UP rounds ties away from zero. The explicit mode controls each line; the private context keeps the arithmetic independent of the caller’s settings. Precision 28 comfortably covers the deliberately bounded inputs. Python documents both rounding modes and local contexts.

Exit Claude, read the resulting invoice.py, and rerun the test command yourself. The local reference implementation passed all six methods. That establishes the behavior of this code against these fixtures, not a success rate for Claude Code.

When reviewing the patch, follow one value all the way through. Does "0.005" enter as a string? Is quantity applied before rounding? Does each rounded line enter the total? Does the returned text keep two decimal places? These are more useful questions than whether the implementation merely imports Decimal.

If the result still differs

If 2.675 still becomes 2.67, look for Decimal(float(price)) or a remaining float conversion. If two separate 0.005 lines total 0.01, the code probably rounds only after summing. If quantity three produces 0.03, it likely rounds the unit price before multiplication.

A failure only under the last test suggests dependence on the caller’s decimal precision or rounding settings. Check that the function establishes its own context and restores the caller’s environment on return. An import error usually means the two Python files are not in the same current folder.

Passing this lab does not make the function a complete invoice service. It trusts the declared input bounds and format. Before accepting outside data, specify validation and rejection behavior separately, including special decimal values and unsupported currencies. Keep the rounding tests when you extend it: they record a product decision that a later “cleanup” could accidentally reverse.

If you next need to compare two existing exports without changing their amounts, use the Gemini CLI CSV reconciliation lab. That task checks recorded values; this one defines how a calculated value is produced.

Sources

Checked November 16, 2026:

Put this to work

Why exact decimal inputs still need a rounding mode and a rounding boundary.

Try

Ask Claude Code to repair one Python function in a disposable practice folder.

Prove it worked

Run six tests against the baseline and reference repair, keeping expected values fixed.

Keep in view

  • Expose two separate errors: float conversion and rounding at the wrong stage.
  • Write a fictional line-rounding policy that an agent can implement without guessing.
  • Check the repair against fixed expected totals and a changed decimal context.
Learn the workflow: Set up your first Claude Code project session