php 47 lines · 8 steps

Precise money math with PHP's BCMath

An invoice calculator that avoids floating-point errors by doing all arithmetic on decimal strings.

Explained by highlit
1final class InvoiceCalculator
2{
3 private const SCALE = 4;
4 
5 public function __construct(private readonly string $taxRate = '0.0825')
6 {
7 }
8 
9 public function total(array $lineItems): array
10 {
11 $subtotal = '0.00';
12 
13 foreach ($lineItems as $item) {
14 $lineTotal = bcmul(
15 (string) $item['unit_price'],
16 (string) $item['quantity'],
17 self::SCALE
18 );
19 
20 if (!empty($item['discount'])) {
21 $factor = bcsub('1', (string) $item['discount'], self::SCALE);
22 $lineTotal = bcmul($lineTotal, $factor, self::SCALE);
23 }
24 
25 $subtotal = bcadd($subtotal, $lineTotal, self::SCALE);
26 }
27 
28 $tax = bcmul($subtotal, $this->taxRate, self::SCALE);
29 $grandTotal = bcadd($subtotal, $tax, self::SCALE);
30 
31 return [
32 'subtotal' => $this->round($subtotal),
33 'tax' => $this->round($tax),
34 'total' => $this->round($grandTotal),
35 ];
36 }
37 
38 private function round(string $amount): string
39 {
40 $shifted = bcadd($amount, '0.005', self::SCALE);
41 return bcmul(
42 bcdiv($shifted, '0.01', 0),
43 '0.01',
44 2
45 );
46 }
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Represent monetary values as strings and use BCMath functions so binary floating-point rounding errors never enter your totals.
  2. 2Carrying extra internal precision (scale 4) and rounding only at the boundary keeps intermediate results accurate.
  3. 3Readonly constructor promotion gives you a configurable, immutable dependency like the tax rate with almost no boilerplate.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Precise money math with PHP's BCMath — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code