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 namespace App\Listeners;
Generating responsive images in a Laravel listener
queued jobs
event listeners
image processing
Intermediate
7 steps
typescript
import { InjectionToken, inject, Provider, isDevMode } from '@angular/core'; import { WINDOW } from './window.token'; export interface AnalyticsConfig {
Layered config with an Angular InjectionToken
dependency-injection
configuration
factory-provider
Intermediate
8 steps
php
<?php namespace App\Jobs;
Debouncing a Laravel shipping-rate job
queues
debouncing
atomic-locks
Advanced
9 steps
php
<?php namespace App\Models\Concerns;
Building soft deletes as an Eloquent trait in Laravel
traits
soft-delete
global-scope
Intermediate
10 steps
php
<?php namespace App\Services;
Idempotent role assignment in Laravel
many-to-many
pivot-data
idempotency
Intermediate
8 steps
php
<?php namespace App\Services;
Merging overlapping busy time blocks in PHP
interval-merging
sorting
datetime
Intermediate
8 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.