Skip to content
Reject Fractional Cents with Python Decimal

Reject Fractional Cents with Python Decimal

November 15, 2026

A payment import can require exact cents even when a calculation elsewhere permits rounding. Trap Inexact during quantize() to reject a value that would lose nonzero digits.

Tested with Python 3.12.14 on Linux. The example uses only the standard library.

Prepare an isolated directory

Run this setup in Bash. If either command fails, stop before saving any files.

practice_dir=$(mktemp -d) && cd "$practice_dir"

Validate before accepting an amount

This parser accepts a string, rejects non-finite values, and limits the magnitude to 999999999.99. A fresh context makes precision and traps independent of the caller’s decimal settings. The 32-character input limit bounds this example’s parsing input; choose an appropriate limit for your own format.

Save as validate_cents.py:

from decimal import Context, Decimal, Inexact, InvalidOperation


def parse_cents(raw: str) -> Decimal:
    if not isinstance(raw, str) or len(raw) > 32:
        raise ValueError("expected a short decimal string")
    context = Context(prec=28, traps=[Inexact, InvalidOperation])
    try:
        value = Decimal(raw, context=context)
        if not value.is_finite() or value.copy_abs() > Decimal("999999999.99"):
            raise ValueError("amount outside the supported range")
        return value.quantize(Decimal("0.01"), context=context)
    except (Inexact, InvalidOperation) as error:
        raise ValueError("amount must be an exact number of cents") from error


for raw in ("12.30", "12.300", "12.301", "-0.005", "NaN", "1000000000"):
    try:
        print(f"{raw}: {parse_cents(raw)}")
    except ValueError as error:
        print(f"{raw}: rejected ({error})")

assert parse_cents("12.300") == Decimal("12.30")
assert parse_cents("-0.00").is_signed()

Run:

python3 validate_cents.py

Output:

12.30: 12.30
12.300: 12.30
12.301: rejected (amount must be an exact number of cents)
-0.005: rejected (amount must be an exact number of cents)
NaN: rejected (amount outside the supported range)
1000000000: rejected (amount outside the supported range)

What this policy accepts

12.300 passes because removing its final zero changes no value. 12.301 and -0.005 require rounding and raise Inexact. Trapping Rounded instead would also reject discarded zeros.

This is a numeric cents rule, not a text-format validator. Decimal strings may contain whitespace, exponent notation or underscores. Add a separate format check if your import forbids those forms. The parser retains signed zero. It also allows negative amounts within its range, which may be useful for credits.

Construct from the original string. Converting a binary float to a string first cannot recover the user’s original decimal input. The explicit context has enough precision for the bounded result; a larger amount policy must reconsider that precision too.

Clean up

From the practice directory, remove only the example file. Return to the previous directory before removing the now-empty temporary directory.

rm -- validate_cents.py
cd - >/dev/null
rmdir -- "$practice_dir"

Reference

Acknowledgements

This post was created with assistance from AI.

Last updated on