Round order lines at the right stage with Python Decimal
See how the same three lines produce 0.15 and 0.14. Validate a CSV rounding contract with six local tests.
In this article
Why the same order has two totals
An order CSV has three identical lines. Each has quantity one, a unit price of 0.05 and a ten-percent discount. The exact net amount of each line is 0.045. An application that rounds each line half up produces a total of 0.15. An application that adds the exact amounts first and rounds the order total with the same rule produces 0.14. Both calculations are internally consistent because they implement different contracts. Refunds, accounting exports and order history expose the difference. This example rounds the net amount of each line to two decimal places and derives the displayed and exported totals from those same values. The currency and the rounding rule belong in the order contract.
Parse the decimal text at the boundary
Converting a CSV field to float first introduces a binary approximation. Passing the float to Decimal preserves that value rather than recovering the original text. Parse the price and the discount rate from the CSV strings directly. The example rejects missing fields, commas as decimal separators, scientific notation and special values such as NaN. A Turkish user interface can still use locale-specific display formatting at the output boundary. The CSV contract stays fixed. Quantity is a positive whole number and the discount rate is between zero and one hundred. Explicit input bounds also make it possible to choose a working precision that covers every accepted row.
Choose the rounding stage and direction
Multiply quantity by unit price and apply the discount before calling quantize to produce two decimal places. The example uses ROUND_HALF_UP, which rounds exact ties such as 0.045 away from zero. Working precision and the number of places in the output are separate decisions in Python's decimal context. A local context with 32 significant digits keeps the bounded calculation stable when surrounding code uses a different precision. Divide the percentage by one hundred and keep the rounded result as a Decimal until it is serialized. The example admits at most eight integer digits and six fractional digits in each decimal field. Update the precision analysis and tests together if those limits change.
import re
from decimal import Decimal, ROUND_HALF_UP, localcontext
DECIMAL_FIELD = re.compile(r"[0-9]{1,8}(?:\.[0-9]{1,6})?")
QUANTITY = re.compile(r"[1-9][0-9]{0,5}")
CENT = Decimal("0.01")
def parse_decimal(field, text):
if not DECIMAL_FIELD.fullmatch(text):
raise ValueError(f"invalid {field}: {text!r}")
return Decimal(text)
def line_amount(quantity, unit_price, discount_pct):
if not QUANTITY.fullmatch(quantity):
raise ValueError(f"invalid quantity: {quantity!r}")
price = parse_decimal("unit price", unit_price)
rate = parse_decimal("discount percentage", discount_pct)
if rate > 100:
raise ValueError("discount above 100 percent")
with localcontext(prec=32):
exact = int(quantity) * price * (1 - rate / Decimal(100))
return exact.quantize(CENT, rounding=ROUND_HALF_UP)
def order_amount(lines):
with localcontext(prec=32):
return sum((line_amount(*line) for line in lines), Decimal("0.00"))
Test neighboring values and the alternate rule
The first test checks that 0.045 becomes 0.05 and that the three rounded lines add up to 0.15. A full discount produces 0.00 with two stored places. A value below the tie, 0.044, produces 0.04. A fourth test records the result of rounding the subtotal once, which is 0.14. Keeping that alternate result visible makes an accidental change in calculation stage easy to spot when the computation moves to a query or another service. Exercise input failures separately. Report the affected row and column in a production importer so that a bad price cannot silently turn into an apparently free product.
import unittest
from decimal import Decimal, ROUND_HALF_UP, localcontext
from order_decimal import CENT, line_amount, order_amount
class OrderDecimalTests(unittest.TestCase):
def test_round_each_line(self):
self.assertEqual(line_amount("1", "0.05", "10"), Decimal("0.05"))
self.assertEqual(order_amount([("1", "0.05", "10")] * 3), Decimal("0.15"))
def test_full_discount_preserves_two_places(self):
self.assertEqual(str(line_amount("1", "15.50", "100")), "0.00")
def test_value_below_tie(self):
self.assertEqual(line_amount("1", "0.044", "0"), Decimal("0.04"))
def test_rounding_only_total_changes_result(self):
self.assertEqual(
(Decimal("0.045") * 3).quantize(CENT, rounding=ROUND_HALF_UP),
Decimal("0.14"),
)
def test_invalid_values(self):
for row in [("1", "NaN", "0"), ("1", "1,25", "0"),
("1", "1.25", "101"), ("0", "1.25", "0")]:
with self.subTest(row=row), self.assertRaises(ValueError):
line_amount(*row)
def test_caller_precision_does_not_change_rounding(self):
with localcontext(prec=3):
self.assertEqual(
order_amount([("1", "299.975", "0")] * 2),
Decimal("599.96"),
)
if __name__ == "__main__":
unittest.main(verbosity=2)
Keep the inputs and the rounded lines
Preserve rounded line amounts with the order total so a refund can refer to the amount actually charged per line. Refunding two of the three example lines yields 0.10 under this contract. Design separate sign, quantity and remaining-balance rules for a real refund workflow. A ledger may store a rounded amount as an integer in the smallest currency unit, accompanied by the currency code. A CSV export may use fixed decimal text. A JSON number read as float can reintroduce the approximation already avoided at input. Agree on an integer or string representation with clients. Storing the line amounts and the rule version also makes later reconciliation possible. Test the export by reading the rounded line strings back and comparing their sum with the stored order total. Decide whether clients may write 0.5 in a field that normally uses 0.50. Both represent the same amount, but a format contract can require exactly two places.
Version the rule when it changes
A new sales channel or payment provider may require a different calculation rule. Reinterpreting old transactions under that rule can change the amount shown on a historical receipt even when the stored inputs stay the same. Apply a new version to the eligible orders. Compare the displayed value, export, refund and reporting totals in a fixture with many low-value lines, full discounts and exact ties. A small reconciliation report with the line identifier, prior value, new value and rule version can explain the difference. This example covers one currency and one scale. When supporting several currencies, obtain the scale from their respective contracts and prevent cross-currency sums at the application boundary.
Reader discussion
What would you change first for maintainability and testing in your own project?
No comments yet. Be the first to contribute.
Write a comment