brick/math
Arbitrary-precision math for PHP. Work with big integers, decimals and rationals reliably, with automatic acceleration via GMP or BCMath when available. PHP 8.2+ supported. Stable 0.x release cycles suitable for production.
composer require brick/math) and factory methods (BigInteger::of(), BigDecimal::of()) reduce integration complexity.app()->make(BigInteger::class)).getPrecisionAttribute()) or raw queries (e.g., BigDecimal::of($row->amount)).0.x.y with backward-incompatible releases (e.g., 0.17.0 removed deprecated methods). Lock to a patch version (^0.17) to mitigate risk.float inputs (use string or fromFloatExact()) to prevent silent precision loss.BigNumber objects interact with Laravel’s type system (e.g., JSON serialization, API responses)?int, float) entirely, or coexist?0.1 + 0.2) that need updating?bcmath()) will be replaced, and what’s their current precision?moneyphp/money) that could conflict?Brick\Math).simPod/phpstan-brick-math for exception type narrowing.+, /, round()).bcdiv()) with BigDecimal::dividedBy().1/3, 0.1 + 0.2).float/int in models/services with BigDecimal/BigInteger.
Example:
// Before
$total = $order->items->sum(fn ($item) => $item->price * $item->quantity);
// After
$total = BigDecimal::sum(
...$order->items->map(fn ($item) =>
BigDecimal::of($item->price)->multipliedBy($item->quantity)
)
);
string or json).bcmath, gmp) in libraries.BigNumber as JSON or use accessors:
protected $casts = [
'amount' => BigDecimal::class,
];
JsonSerializable).BigDecimal as the underlying precision engine (e.g., wrap brick/math in a Money class).math.php or phpmath with brick/math for consistency.string for BigDecimal).BigDecimal::equals() or isEqualTo().^0.17) to avoid breaking changes.RoundingMode constants).BigNumber usage patterns (e.g., "Use BigDecimal for all monetary values").brick/math to CI checks (e.g., PHPUnit, Pest).BigNumber usage where needed.MathException for centralized error handling.toString() for logging (e.g., logger()->debug($bigDecimal->toString())).BigInteger::sqrt() results).float inputs.brick/math’s built-in tests).BigNumber objects are immutable and lightweight (no overhead beyond storage).| Scenario | Risk | Mitigation |
|---|---|---|
| GMP/BCMath unavailable | Performance degradation | Fallback to pure PHP; monitor with APM tools. |
| Invalid inputs | NumberFormatException |
Validate inputs early (e.g., regex for BigDecimal strings). |
| Division by zero | DivisionByZeroException |
Use try-catch or guard clauses (e.g., if ($denominator->isZero())). |
| Rounding errors | Silent precision loss | Enforce RoundingMode::Unnecessary where exactness is critical. |
| Serialization issues | Corrupted data | Test cross-machine serialization (e.g., cache/queue systems). |
| Version upgrades | Breaking changes | Pin to patch versions; test upgrades in staging. |
How can I help you explore Laravel packages today?