Last reviewed: November 1, 2026

Direct answer

Preserve sub-cent AI request costs in decimal arithmetic or sufficiently fine integer units, then round at an explicitly defined boundary. AI API cost rounding needs separate rules for calculation, budget reservation, financial posting, and display. Formatting a request as $0.00 must not replace the amount used to calculate a workload total.

For a hypothetical rate card, 800 input tokens at $0.25 per million and 200 output tokens at $1.00 per million cost $0.0004 together. Across 100,000 identical requests, the calculated total is $40.00. Rounding every request to cents first produces $0.00; rounding every positive request upward to a cent produces $1,000.00. These are locally checked arithmetic examples, not provider prices or observed billing results.

Preserving detail does not override a supplier’s billing contract. If the supplier documents per-request rounding, minimum charges, or another grouping rule, reproduce that rule in the billing calculation while retaining the underlying usage and intermediate values.

Who this is for

This guide is for platform engineers, data engineers, and FinOps owners building request-cost ledgers, budget checks, or team chargebacks. It is especially useful when a dashboard contains many zero-cost rows, totals change after a database migration, or finance and engineering disagree by amounts that grow with request count.

The design below is an engineering recommendation based on three official technical references. It covers numerical representation and rounding controls. A current rate card and account billing terms are still needed to calculate a particular supplier’s charges.

Key takeaways

  • Keep usage quantities, rate denominators, monetary amounts, and currency codes in separate fields.
  • Preserve small calculated amounts through storage and aggregation; apply the approved rounding rule at its recorded boundary.
  • Define precision and rounding mode in both application code and database writes.
  • Keep conservative reservations separate from calculated usage costs and invoiced amounts.
  • Reconcile differences with evidence instead of changing a rate until totals happen to match.

Sources checked

Three primary public references were checked on November 1, 2026:

  • PostgreSQL: Numeric Types , served as PostgreSQL 18 documentation, recommends numeric for monetary quantities requiring exactness. It explains that a declared column scale rounds incoming values and that numeric rounds ties away from zero.
  • Python: decimal — Decimal fixed-point and floating-point arithmetic documents decimal construction, arithmetic contexts, finite precision, rounding modes, and quantize(). Constructing a decimal from a binary float preserves that float’s value, which can differ from the intended decimal text.
  • Stripe: Supported currencies documents payment API amount units, including 1000 for 10 USD and 10 for 10 JPY, plus currency-specific exceptions. It supports the payment-unit examples here; it does not establish an AI supplier’s billing or rounding policy.

These are maintained technical references supporting an evergreen implementation task, rather than announcements of a recent pricing change. Verify the deployed library and database versions and the payment endpoint’s current currency rules before adopting the design.

Contract details to verify

Define each amount before choosing its type

Write a short numerical contract for every stage:

StageValue to preserveBoundary to define
Usage ingestionOriginal quantity, unit, and usage evidenceValidation and duplicate handling
Rate ingestionDecimal rate text, currency, denominator, and revisionEffective period and eligible usage category
Cost calculationAmount before posting or display roundingArithmetic precision and any required intermediate rounding
Budget reservationConservative commitment in declared unitsApproved upward-rounding rule for positive holds
Financial postingCalculated subtotal and posted amountGrouping key, currency scale, and rounding mode
Display or paymentFormatted value or endpoint amountDisplay precision or payment-specific unit conversion

For the hypothetical token example, the input component is 800 × 0.25 / 1000000 = 0.0002 USD. The output component is another 0.0002 USD. Record the denominator explicitly: a rate per million tokens is not a rate per token, and a currency amount is not a token counter.

Store the rate revision and calculation-policy version with the result. Historical costs must remain reproducible when a rate changes. For a rerun, retain the original calculation and identify the corrected version rather than silently replacing the evidence.

Carry sufficient precision across every boundary

Use a decimal implementation with an explicit arithmetic context, or scaled integers whose unit can represent the supported calculations. Neither choice is automatically sufficient. An integer field labeled amount is ambiguous without its currency and scale; a decimal can still round when its context or destination column has insufficient precision.

In a decimal pipeline, parse the original decimal text directly. Converting a rate to a binary float and then to decimal does not recover information lost at the first conversion. Python’s documentation demonstrates this distinction and also warns that insufficient decimal precision can break arithmetic identities.

Choose precision using the smallest supported rate, rate denominator, largest usage quantity, adjustments, and largest aggregate. Test those bounds through the actual parser, calculator, database driver, export, and reimport path. Reject nonfinite values, invalid units, and amounts outside the supported range before they enter a budget decision. Missing or invalid cost must remain unresolved instead of becoming zero.

Review database scale separately. A PostgreSQL numeric(20,2) column rounds a sub-cent amount on insertion even though numeric is an exact decimal type. A later SUM cannot reconstruct the discarded digits. Select storage precision from the numerical contract, and detect unsupported scale before a write that would silently round it.

Specify grouping and tie handling together

When the approved calculation has no intermediate rounding, its shape is:

component_cost = usage_quantity × decimal_rate / rate_denominator
group_subtotal = sum(component_cost for the documented billing group)
posted_amount = round(group_subtotal, posting_scale, posting_mode)

The grouping key can include billing account, currency, period, model, or usage category, depending on the applicable contract. Preserve those dimensions until their rates and rounding rules have been applied. Aggregating everything first can be wrong when rates, tiers, minimums, or required rounding differ.

Name the tie rule. Python’s default decimal context uses half-even, while PostgreSQL documents ties away from zero for numeric. At cent precision, 0.005 becomes 0.00 under half-even and 0.01 under half-up. These are different policies with valid uses; allowing a driver or database cast to choose accidentally creates drift.

Signed corrections need the same care. Under half-up, -0.005 becomes -0.01. Do not apply a positive-reservation ceiling to every credit or take absolute values to simplify settlement. Record each correction’s identity, sign, reason, and original evidence reference.

Separate reservations, postings, and payment units

A reservation may deliberately round a positive upper-bound estimate upward to the ledger’s smallest unit. For example, with one million internal units per USD, a $0.0004001 estimate needs a 401-unit hold. Preserve the original estimate and the 401-unit reservation separately. Settlement replaces the hold with the calculated cost under the settlement policy; it must not present the conservative hold as measured consumption.

Integrate that representation with an atomic AI API budget reservation ledger . Exact arithmetic alone does not stop two workers from spending the same available balance.

A payment API has another boundary. Stripe’s USD and JPY examples show why multiplying every amount by 100 is unsafe. Resolve the currency and endpoint rules before constructing a payment amount. Keep any currency conversion and its rate evidence explicit; changing the currency label does not convert an amount. Payment minor units do not dictate the precision of the internal usage ledger.

Failure modes

Display values become accounting inputs. An export contains only two-decimal request amounts, so expensive aggregate usage appears free. Export the retained calculation amount and currency separately from the formatted display value.

Application and database disagree on ties. A calculator uses half-even, then a column cast applies another rule. Apply the intended posting rule explicitly and test storage readback with positive and negative ties.

A finer integer scale is assumed to solve every rate. A supported rate produces fractions smaller than the chosen unit. Increase precision, retain a remainder, or define a bounded rounding policy. Document the resulting error budget instead of calling the representation lossless.

Every invoice difference is dismissed as rounding. Missing usage, duplicate records, discounts, tax, currency conversion, and reporting timing require separate explanations. Preserve calculated cost, supplier subtotal, and the identified difference. Use the billing-period close workflow before treating a provisional source total as ready for financial close.

Verification before rollout

Run these acceptance checks against the complete data path. The hypothetical arithmetic above was checked locally; this table describes checks for your implementation, not a reported production deployment.

CheckRequired observation
100,000 example requestsRetained calculation amounts sum to $40.00 before any contract-specific adjustments
Positive and negative half-cent tiesApplication, storage, and posting produce the approved results
Export and reimportCurrency, scale, amount, and policy revision survive without float coercion
Maximum quantity and aggregateNo overflow or unnoticed precision loss within declared bounds
Nonfinite, missing, or malformed inputExplicit rejection or unresolved state; no zero-cost fallback
Duplicate correctionThe same correction identity cannot change the balance twice
Alternative batch sizesIdentical results when the documented policy permits regrouping without intermediate rounding
Invoice comparisonEvery difference has an identified cause or remains open for investigation

When team chargebacks must add to a rounded parent total, define how the residual is allocated. Retain the amounts before allocation and use a deterministic, documented tie-break rule. Independently rounding each team’s share can leave the sum different from the parent; hiding the residual changes the apparent cost.

FAQ

Are integer cents enough for an AI request ledger?

Only if the contract’s smallest required amount is representable in cents. The hypothetical $0.0004 request is not. Finer scaled integers can work, but their scale, supported bounds, and treatment of smaller fractions must be explicit.

Does decimal arithmetic guarantee invoice agreement?

No. It addresses numerical representation within its precision limits. Agreement also depends on complete usage, correct rates, grouping, minimums, adjustments, currency rules, and the supplier’s actual billing policy.

Should every request be rounded upward for safety?

An explicitly conservative reservation can round upward to its declared unit. Calculated usage and invoice reproduction need their own documented rules. Carrying the reservation amount forward as actual cost can materially overstate spend.

What if the supplier does not explain its rounding boundary?

Keep a reproducible estimate and label it accordingly. Preserve intermediate amounts and request account-specific clarification before claiming exact invoice reproduction. An unexplained difference remains unresolved, even when it looks small.

Reader next step

Choose one workload and trace a day’s costs from rate text to usage calculation, database storage, export, and final report. Record currency, units, precision, grouping, rounding mode, and policy revision at each boundary. Locate the first irreversible rounding operation and confirm that it belongs there.

Then run the sub-cent total, tie, and export checks before changing a budget or chargeback. Keep the original ledger during the comparison, explain each difference, and approve the numerical contract with both its engineering owner and finance consumer.