When Two Decimal Places Cost You Four Cents

Say a customer buys eight washers at twelve and a half cents apiece. That's a dollar. I can do that one in my head, which makes it a little embarrassing when the invoice comes back at $1.04.

I'd start with the price on the invoice line. If it says 0.13, the multiplication checks out. Eight times thirteen cents is a dollar four. So where did the half-cent go?

Suppose we gave the unit price a PostgreSQL column of numeric(10, 2). Ask Postgres to fit 0.125 into that column and it rounds to 0.13. You can reproduce the whole bug without starting Rails or involving a floating-point number.

SELECT 0.125 * 8 AS quoted_total,
       0.125::numeric(10, 2) * 8 AS billed_total;
-- quoted_total = 1.000, billed_total = 1.04

What goes on either side of the comma?

The first number is precision, the total number of digits the column allows. The second is scale, which gives us two places after the decimal point in this example. That leaves eight on the left, so the largest unit price we can store is 99,999,999.99. Change the declaration to numeric(18, 2) and I can sell you a much more expensive washer. I still can't sell you this one at the price I quoted. PostgreSQL numeric types

If the supplier quotes to four decimal places, I'd carry all four into the unit-price column. For a new column, Rails lets me put that right in the generator command. The quotes keep the shell from expanding the braces.

bin/rails generate migration AddUnitPriceToBillingLines 'unit_price:decimal{12,4}'

That generates precision: 12, scale: 4. We still have eight digits on the left, and now we can keep a quote like 0.1251 intact. Rails migration modifiers

I'd also want to know if the supplier started sending a fifth decimal place. Say the import gets the string "0.12506". By the time a Rails validation reads line.unit_price, it can already see 0.1251, even before the record is saved. I'd check the original string at import. If the check lives on the model, unit_price_before_type_cast gives me what was actually assigned. After a reload, all I have on that row is the four-place price. Rails attributes before type casting

When does half a cent become a cent?

“Store money as integer cents” works fine for the dollar I'm going to collect. What integer would I put on the washer, though? The supplier quotes a price per unit. The customer pays the total. Those two amounts can reasonably need different numbers of decimal places.

Here's the invoice I'd take to whoever owns the customer agreement. It has two separate lines at half a cent apiece. Round each line half up and the customer owes two cents. Add the unrounded lines first and the customer owes one cent. I want an answer to that question before accounting ships one calculation and checkout ships the other.

For this example, we agree on one cent. We multiply each USD unit price by its quantity, add the results, then round once to the nearest cent, half up. Here's the arithmetic inside InvoiceAmount.cents. The inputs are decimal prices and positive integer quantities.

total = lines.sum(BigDecimal("0")) { |price, quantity| price * quantity }
cents = (total * 100).round(0, BigDecimal::ROUND_HALF_UP).to_i

Active Record gives me a BigDecimal for a decimal column. In the tests I build prices from strings so they take the same path through the calculation. I'd keep both of these cases.

# Rounding the unit price first would charge 104 cents.
InvoiceAmount.cents([[BigDecimal("0.125"), 8]]) # => 100

# Rounding each line first would charge 2 cents.
half_cent = BigDecimal("0.005")
InvoiceAmount.cents([[half_cent, 1], [half_cent, 1]]) # => 1

I'd also run the eight washers through the importer and reload the line from Postgres. A calculator test can pass all day if I hand it a price the real column can't store.

I'd carry the two half-cent lines all the way through the receipt and the accounting export. If the receipt shows two $0.01 lines above a $0.01 total, the customer has a perfectly reasonable question. I'd print $0.005 on each line so they can do the same math we did.

What about the invoices we've already sent?

The first record I'd go looking for is the supplier's original quote. Widening the old column turns 0.13 into 0.1300. Was the quote 0.125? Was it 0.134? Both would have produced the record I'm looking at. Those two extra zeroes haven't told me anything.

For new quotes, I'd run the old and proposed calculations side by side while checkout still uses the old result. Wherever they disagree, I want to see the original quote and the first line where the numbers diverge. Once we can explain those differences, I'd switch newly finalized invoices over. An issued invoice keeps its prices, currency, rounding rule and final amount in cents. If we owe somebody four cents on an earlier sale, I'd issue a credit tied to that invoice. Now accounting can explain both what we charged and what we gave back.

We got the dollar right. Did we charge it twice?

Say the customer clicks Pay. The provider charges the dollar. Our worker times out waiting for the response. We know the customer owes us 100 cents. All the timeout tells us is that our worker never heard back. What do we send when the job runs again?

In the sample there's one full USD payment per finalized invoice. ChargeInvoice reads the amount from the issued invoice and commits a pending payment row before contacting the provider. A unique index on the invoice ID keeps two workers from creating separate rows. Recovery takes just service.resume(invoice_id: id). Even if I deploy a new calculator overnight, the worker has yesterday's 100 cents right there.

reference = @gateway.charge(
  invoice_id: attempt.invoice_id,
  cents: attempt.amount_cents,
  currency: "USD",
  key: "invoice/#{attempt.invoice_id}"
)

That index settles how many rows we can have in our database. Two workers can still read the same row and both make the call. At the provider, every submission for this payment uses the same idempotency key, the same parameters and the same merchant account. When we confirm the payment succeeded, we save its reference. The invoice ID works here because we collect once per invoice. If we add installments later, each installment needs its own key.

I'd put the age of the oldest pending charge on the payments dashboard. The sample gives automatic retries 12 hours. Retrying a payment doesn't restart the clock. Stripe's v1 API can prune a key once it's at least 24 hours old. After that, even resending the original key can create a new payment. I'd alert the person responsible before our 12 hours are up, then stop automatic submissions at the cutoff. They can use the invoice ID to find the provider's record and check the merchant account, currency, amount and payment status. If they can confirm the dollar went through, they can record its reference. If they still can't tell, the row stays pending. Stripe's idempotent request behavior

The worker test I'd write first lets the fake provider take the money and then raise the timeout. The order matters. A fake that always raises before it records the dollar never tests what happens when we've already taken the customer's money.

gateway.failure = :after
expect { charge }.to raise_error(Timeout::Error)
expect(gateway.payments.size).to eq(1)

gateway.failure = nil
expect(service.resume(invoice_id: invoice_id).state).to eq("succeeded")
expect(gateway.payments.size).to eq(1)

The sample also sends two workers into the fake gateway together. I'd take that case to the provider's sandbox, too. Stripe v1 can return a temporary 409 if the first request is still running when the second one arrives. Give it time, then retry with the same key and parameters inside the retry window. It might take more than two requests for both workers to get an answer. Stripe's guidance on concurrent requests

If the customer emails me tomorrow and says, “Hey, I think I paid twice,” I want to be able to pull up those eight washers, follow the reference to one successful charge for a dollar, and send them the receipt. I wouldn't ask them to take my worker's word for it either.

Download the service, PostgreSQL migration and RSpec suite.