A washer costs an eighth of a dollar. A customer buys eight. You can work out the invoice in your head, which makes it a little embarrassing when the app comes back with $1.04.
Where did the extra four cents come from? Suppose we gave the unit price a PostgreSQL column of numeric(10, 2). The database can store $0.12 or $0.13 in that column. Give it $0.125 and it rounds to $0.13. By the time Rails multiplies the price by eight, those four cents are already on the bill.
What goes on either side of the comma?
The first number is precision, the total number of digits. The second is scale, the number of places to the right of the decimal point. With numeric(10, 2), eight digits are available on the left and two on the right. The largest positive value is 99,999,999.99. Changing the declaration to numeric(18, 2) buys room for a bigger invoice. It still loses the half-cent on a washer. PostgreSQL numeric types
Suppose our supplier quotes prices to four places. I'd carry all four into the unit-price column. Rails lets you put both numbers right in the generator command. The quotes keep the shell from expanding the braces.
bin/rails generate migration AddUnitPriceToBillingLines 'unit_price:decimal{12,4}'
The migration gives you precision: 12, scale: 4. That's still eight digits on the left, now with room for 0.1251. I'd check the incoming quote before assigning it to the Rails attribute. Try saving 0.12505 and reading it back. You get 0.1251. A validation that only sees the stored value has already missed the supplier's fifth digit. Rails decimal column options
At what point does a fraction become a cent?
I'd put a second invoice in front of whoever owns the customer agreement. It has two lines at half a cent each. Should the customer owe one cent or two? Either answer fits in the database. If accounting rounds each line and checkout rounds the total, both teams can pass their own tests and still disagree about what the customer owes.
For this example we agree on one cent. Add the extended line amounts, then round the USD total once, half up. I'd put that invoice in the calculator tests and use it to check the receipt and accounting export. On the receipt I'd show the two half-cent amounts with enough places for a reader to add them up. Printing two one-cent lines above a one-cent total would invite a perfectly reasonable support call.
InvoiceAmount.cents owns the arithmetic. It accepts 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 returns a decimal column as a BigDecimal. When building an example by hand, I use a decimal string so the price never takes a trip through a binary float.
InvoiceAmount.cents([[BigDecimal("0.125"), 8]]) # => 100 InvoiceAmount.cents([[BigDecimal("0.1251"), 100]]) # => 1251
How I'd change a system that's already billing people
The first record I'd look for is the supplier's original quote. If the old column says 0.13, widening it gives me 0.1300. It can't tell me whether the supplier quoted 0.125 or 0.134.
For new quotes, I'd calculate the old and proposed totals side by side while checkout still uses the old result. I'd start the review with invoices where the two disagree and trace the first differing line back to its quote. Then I'd switch newly finalized invoices to the agreed rule. An issued invoice keeps its quoted lines, currency, rounding rule and settled cents. If a customer is owed four cents on an earlier sale, a credit tied to that invoice gives both the customer and accounting a record of what changed.
What if the charge succeeds and the response gets lost?
The customer clicks Pay. The provider charges a dollar. Our worker times out waiting for the response. All the worker knows is that it didn't hear back. If it treats the retry as a new payment, a perfectly calculated dollar can become two.
The sample starts with one full USD payment per finalized invoice. On the first submission, the worker reads the amount from the issued invoice in our database. ChargeInvoice commits a pending row with that invoice ID and those cents. A unique index gives two workers the same row. For recovery, the job calls service.resume(invoice_id: id). That's its entire input. Even if we deploy a new calculator between checkout and collection, yesterday's dollar still goes to the provider as 100 cents.
reference = @gateway.charge( invoice_id: attempt.invoice_id, cents: attempt.amount_cents, currency: "USD", key: "invoice/#{attempt.invoice_id}" )
The database index can stop a second local row. Only the provider can tell us whether it moved the money. That's why every submission carries the same idempotency key, amount and currency to the same merchant account. Once we have a confirmed payment reference, we save it. Two separate invoices for a dollar still get two distinct keys. An invoice ID works here because we collect once per invoice. If we introduced installments, each installment would need its own payment identity.
I'd put the age of the oldest pending charge on the payments team's dashboard. Stripe's v1 API can prune keys once they're at least 24 hours old. The example gives automatic retries 12 hours. I'd surface an unresolved payment to its owner before that window closes. At the cutoff, the worker stops. The person investigating needs the invoice ID, merchant account, expected cents and provider-side evidence. If the provider confirms a matching payment, record its reference. If the evidence is inconclusive, leave the payment pending. A new key would let a second dollar through. Stripe's idempotent request behavior
Two tests I'd write first
The arithmetic test that earns its keep is the one where rounding at the wrong step gives a different answer. Eight washers do that nicely. For the worker, I'd have the fake provider record the payment and then raise a timeout. A fake that always fails before accepting the money misses the exact bug we're looking for.
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 suite also runs two workers into the fake gateway together. The expected result is two requests, one payment, and one reference both workers can hand back. That's the assertion I'd carry into a real provider's sandbox. The local test tells me what our workers do. The adapter test has to show what the provider does when that second request arrives. Download the service, PostgreSQL migration and RSpec suite.