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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Represent monetary values as strings and use BCMath functions so binary floating-point rounding errors never enter your totals.
- 2Carrying extra internal precision (scale 4) and rounding only at the boundary keeps intermediate results accurate.
- 3Readonly constructor promotion gives you a configurable, immutable dependency like the tax rate with almost no boilerplate.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/precise-money-math-with-php-s-bcmath-explained-php-a6fb/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.