Complete worked example
python
import re
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP, localcontext
def amount(values):
if not isinstance(values, list) or len(values) > 1000:
raise ValueError("at most 1000 amounts required")
with localcontext() as context:
context.prec = 28
try:
numbers = []
for value in values:
if not isinstance(value, str) or len(value) > 16 or not re.fullmatch(r"[0-9]+(?:\.[0-9]{1,4})?", value):
raise ValueError("bounded decimal strings required")
number = Decimal(value)
if not number.is_finite() or number < 0:
raise ValueError("finite nonnegative values required")
numbers.append(number)
total = sum(numbers, Decimal("0"))
return format(total.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP), "f")
except InvalidOperation as error:
raise ValueError("invalid decimal amount") from error- Reasoning
- Keep decimal inputs exact and state when and how a report rounds its result. Compare the stated values and failure boundary before changing the implementation.