The cart shows one total, the payment another. Who got it wrong?
One cart, three exact totals: why cents and BigInt cannot choose discount, shipping and refund rules for the team. Calculations, Dart code and client-server responsibilities.
- Published
- October 21, 2026
- Verified
- October 21, 2026
The cart shows one total, the payment another. Who got it wrong?
A cart contains three different items at $99.90 each. A 15% discount applies to the order. The app shows $254.76 for the goods. At payment, the customer discovers that the amount is actually $254.74.
The difference favours the customer. It might seem too small to investigate: two cents, not two million. But the amount they were about to confirm has just changed without any change to the order. Return one item later, and the same uncertainty will reappear elsewhere in the system.
The first suspect is usually double. Someone remembers binary floating-point errors, suggests storing money in cents and prepares to close the issue. Except exact arithmetic won’t eliminate this discrepancy. The app and server can execute different rules without making an arithmetic mistake.
The cart is hypothetical. The calculation is concrete: it shows which decision went missing between “apply a 15% discount” and the amount on the payment button.
Three correct calculations, one rule to choose
Before discount, the goods cost $299.70. There are at least three ways to proceed. To make the comparison fair, each uses the same rule: round to the nearest cent, with an exact half-cent rounded up. For now, all amounts are nonnegative.
| What gets rounded | Calculation | Goods payable |
|---|---|---|
| Each item’s discounted price | 99.90 × 0.85 = 84.915 → 84.92; then × 3 | $254.76 |
| The order discount | 299.70 × 0.15 = 44.955 → 44.96; subtract from 299.70 | $254.74 |
| The discounted order total | 299.70 × 0.85 = 254.745 → 254.75 | $254.75 |
The discount has the same name in all three cases. Every calculation can use exact decimal arithmetic. The difference comes from where rounding happens, not from the processor’s inability to count money.
The last two rows are particularly easy to overlook. “Subtract fifteen percent” and “keep eighty-five percent” seem certain to agree. Before rounding, they do. After independently rounding the discount or the remainder, they don’t always agree.
“Round to two decimal places” specifies none of these choices. It also needs an object and a point in the calculation: unit price, order line, discount or total. Then comes the rule for a halfway value. Even Dart’s standard double.round() has a particular rule: halfway values round away from zero. Calling round() does not establish that the team agreed on the right business rule.
The rest of this example uses the second approach: calculate the discount on eligible goods, round it to a cent and subtract it from their total. That is the rule of this illustrative order, not a recommendation for every promotion.
Cents solve one problem, not every problem
Storing $99.90 as 9990 cents is a reasonable way to represent that amount exactly. Multiplying it by 15% still produces a fractional number of cents. The application still needs to decide what happens to the half.
double serves a different purpose: it is an IEEE 754 floating-point number. Not every decimal value has an exact representation. Building monetary calculations around repeated double conversions and hoping toStringAsFixed(2) will fix the result is therefore a poor way to specify the rules. A formatter produces a string, not an agreed order calculation.
Switching to an exact decimal type won’t select a row from the table either. A package can multiply, add and round precisely. The application still decides what to multiply and when to round.
For a small check, a percentage can be represented as a ratio of integers. Fifteen percent is 15 / 100; there is no need to create an intermediate 0.15. The chosen rounding rule can be explicit:
BigInt roundHalfUp(BigInt numerator, BigInt denominator) {
if (numerator.isNegative || denominator <= BigInt.zero) {
throw ArgumentError('Expected a nonnegative ratio');
}
final whole = numerator ~/ denominator;
final remainder = numerator % denominator;
return whole +
(remainder * BigInt.two >= denominator ? BigInt.one : BigInt.zero);
}
The function takes the whole part first. If the remainder is at least half the denominator, it adds one minor unit. For this order:
final goodsMinor = BigInt.from(29970);
final discountMinor = roundHalfUp(
goodsMinor * BigInt.from(15),
BigInt.from(100),
);
final payableGoodsMinor = goodsMinor - discountMinor;
// discountMinor == 4496, payableGoodsMinor == 25474
BigInt provides arbitrary-precision integer arithmetic here. It is not a mandatory money type for every shop. With ordinary int, the input range and intermediate products need to fit. Dart compiled to JavaScript also has a different exact-integer range from native Dart. Converting an already inexact double to BigInt cannot recover the lost precision.
This function deliberately rejects negative values. Operations that can have a negative amount need a separate halfway rule. The refund below is stored as a positive amount to return and subtracted from the paid balance, not passed into the function as a negative discount.
An order discount needs an allocation
The order has a $44.96 discount. It also has three items. How much of that discount belongs to each?
During payment, it is easy not to ask: the total reconciles. The question becomes unavoidable when one item is returned. Recalculate every refund as 99.90 × 0.85, rounded to a cent, and each refund is $84.92. Three such refunds total $254.76, although the goods were paid for at $254.74.
A “never refund more than the payment” check will stop the last one. Support will then have to explain why the last of three items unexpectedly has a different refundable amount.
In this example, the discount is allocated across eligible lines in proportion to their original value. First, each line receives its share rounded down to whole cents. Remaining cents go to the lines with the largest fractional remainders. Equal remainders are resolved by a predetermined ordering of permanent line IDs.
The shares here are equal: 44.96 / 3 = 14.98666… dollars. Allocating $14.98 to each line accounts for only $44.94. The remaining two cents go to A and B:
| Line, one unit | Original price | Allocated discount | Paid for the item |
|---|---|---|---|
| A | $99.90 | $14.99 | $84.91 |
| B | $99.90 | $14.99 | $84.91 |
| C | $99.90 | $14.98 | $84.92 |
| Total | $299.70 | $44.96 | $254.74 |
That is one explicit allocation policy, not a universal property of percentage coupons. Another promotion might use a different basis, exclude some items or impose separate limits. What matters here is that line discounts add up to the order discount and no line becomes negative. The interface needs to show those allocated amounts: putting $84.92 under every item out of habit would reintroduce the contradiction after the calculation had been fixed.
Display order should not affect the allocation. If the current list position resolves a tie, sorting by name will move a cent between items. A permanent ID is needed to keep that decision stable, not to make the model look more sophisticated.
For a return of B under this policy, its paid value is already known: $84.91. After that refund, $169.83 remains accounted for against the other goods. There is no need to fetch today’s catalogue price and apply today’s promotion to yesterday’s purchase.
Each line in the table contains one unit. If a line contains three and individual returns are allowed, allocation is needed within the line too. Dividing its amount by quantity and rounding anew for each refund can create another extra cent. Already refunded units and unfinished refund attempts also need tracking so the same amount is not returned twice.
Shipping need not share the discount
Adding $15 shipping is straightforward. It is excluded from this promotion, so the total is $254.74 + $15 = $269.74. If the client discounts everything including shipping while the server discounts only goods, another discrepancy appears. An exact number type won’t help.
There is a more visible question. Suppose shipping is free from $280. Is that threshold checked before or after the discount? This cart has $299.70 before discount and $254.74 after it. The answer changes the entire shipping charge, not just a cent.
The threshold is an assumption of this example, not a claim about a particular service. The business needs to specify it alongside eligible items, the order of multiple discounts and return conditions. “Normal cart behaviour” can conceal several incompatible expectations.
Whether the original order’s conditions survive a partial return is a separate decision. This example refunds the saved paid share of the item and treats shipping separately. A real product’s permitted conditions need agreement with the people responsible for sales, accounting and applicable requirements. An arithmetic algorithm neither determines customer rights nor justifies inventing deductions.
A payment API doesn’t decide the shop’s discount allocation either. For example, Stripe’s refund documentation describes a partial refund against an original payment with a specified amount. The application must establish the returned item’s amount from its agreed order data before making that request, while respecting the provider’s constraints.
The server should return a calculation, not a mystery total
Receiving total: 269.74 is not enough if the client continues calculating line amounts independently. The bottom of the screen will be correct, while the items above it won’t add up. “Always show the server total” would merely move the contradiction higher up the screen.
For this model, the server returns a calculation with an ID, cart revision, currency and amount breakdown. For example:
{
"calculation_id": "checkout-17",
"cart_revision": 12,
"currency": "USD",
"goods_subtotal_minor": "29970",
"discount_total_minor": "4496",
"shipping_minor": "1500",
"payable_minor": "26974",
"lines": [
{"line_id": "A", "quantity": 1, "paid_minor": "8491"},
{"line_id": "B", "quantity": 1, "paid_minor": "8491"},
{"line_id": "C", "quantity": 1, "paid_minor": "8492"}
]
}
This is an application response example, not Stripe’s request format or a complete payment protocol. The suffix minor means minor units of the chosen currency: cents for USD here. Encoding the integer as a string allows it to cross a JSON boundary without passing through a client-side numeric representation with an unsuitable range.
The scale cannot be guessed from the field name. Not every currency has a hundred minor units. Stripe documents zero-decimal currencies and special amount representations separately. An adapter needs to map the internal model to the provider’s contract, not multiply everything by a hundred. Stripe’s integer amount is one external representation; the application’s string encoding is another. Neither requires using double internally.
The calculation ID identifies the amount the customer is confirming. The cart revision helps reject an old response after a quantity or address change. Before creating a payment, the server checks that the contents, conditions and prices remain valid rather than trusting the amount submitted by the client. If the offer has changed, the customer needs the new calculation before confirming, not an explanation after reaching payment.
For responsive interaction, the client can estimate the price locally. Its rules must agree with the server’s, and the provisional nature of the amount needs to be clear. Checking both implementations against the same inputs is more useful than assuming similarly named methods perform the same calculation.
After purchase, the agreed contents and allocations are saved with the payment reference. A refund uses the history of the paid order, not an invitation to run today’s calculator. Requesting a refund, receiving a provider response and confirming completion remain different states; a saved item amount doesn’t prove the money has been returned.
What to check before connecting payments
A small local Dart check reproduced the three rounding outcomes. The chosen allocation conserved the order discount, stayed within each line’s value and remained unchanged when input lines were reordered. This checks finite sets of calculations, not a shop, payment API or complete refund system.
A project needs more than “two items at a hundred each.” Check half-cent boundaries, zero and full discounts, ineligible items, line reordering, several units in one line, shipping thresholds and successive partial refunds. Concurrent refunds need protection against accounting for the same paid share twice; exact arithmetic alone is not enough.
Before implementation, the team needs unambiguous answers: what the percentage applies to, what gets rounded and when, how remainders are allocated, whether shipping participates, and which conditions survive a return. Those decisions then become the calculator’s inputs, outputs and checks.
That makes the question in the title answerable. The mistake isn’t necessarily on the side showing more or less. It is letting different parts of the product independently decide what the same order cost, then trying to reconcile their answers with a string formatter.
ArkTelos Lab: engineering journal · ArkTelos website
Channels: ArkTelos Lab EN · ArkTelos Lab RU · ArkTelos EN · ArkTelos RU
Result boundaries
- The cart and its policies are hypothetical. Finite local Dart arithmetic checks are not shop or payment-integration tests. JavaScript/Wasm, concurrent refunds, database persistence and legal or tax conditions were not tested.
Telegram edition