php-standard-library/math
Strictly typed math utilities for PHP with predictable, consistent error handling. Part of the PHP Standard Library project, providing reliable mathematical functions and a stable developer experience for safer numeric operations.
Installation
composer require php-standard-library/math
Add to composer.json under require if not auto-loaded.
First Use Case
use Math\Math;
// Basic arithmetic with type safety
$result = Math::add(5, 3); // Returns 8 (int)
$result = Math::divide(10, 3); // Returns 3.333... (float)
Where to Look First
Math::add(), Math::subtract(), Math::multiply(), Math::divide()Math::sqrt(), Math::pow(), Math::log()Math::safeDivide() (returns null on division by zero)src/Math.php for full method signatures and edge-case behavior.Type-Safe Calculations
// Laravel Service Layer Example
public function calculateDiscount(float $price, float $percentage): float
{
return Math::multiply($price, Math::divide($percentage, 100));
}
Error Handling
try {
$result = Math::safeDivide(10, 0); // Returns null
} catch (InvalidArgumentException $e) {
// Fallback logic
}
Batch Operations
$sum = 0;
foreach ($prices as $price) {
$sum = Math::add($sum, $price);
}
Laravel Facade (Optional) Create a facade for cleaner syntax:
// app/Facades/MathFacade.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class MathFacade extends Facade {
protected static function getFacadeAccessor() { return 'math'; }
}
Register in AppServiceProvider:
$this->app->bind('math', function () {
return new \Math\Math();
});
Usage:
use App\Facades\MathFacade as Math;
Math::add(5, 3); // Now works as a facade
Validation Integration
use Math\Math;
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'percentage' => 'required|numeric|max:100',
'price' => 'required|numeric|min:0',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()]);
}
$discountedPrice = Math::subtract(
$request->price,
Math::multiply($request->price, Math::divide($request->percentage, 100))
);
Strict Typing
Math::sqrt() throw InvalidArgumentException for negative inputs.Math::safeSqrt() for nullable results or validate inputs first.Floating-Point Precision
Math::divide(1, 3) returns 0.3333333333333333 (not 0.333...).$rounded = Math::round(Math::divide(1, 3), 2); // 0.33
Division by Zero
Math::divide(10, 0) throws DivisionByZeroError.Math::safeDivide() for APIs or use try-catch blocks.Large Numbers
PHP_INT_MAX may overflow silently.Math::bigIntAdd() (if available) or GMP functions for arbitrary precision.Enable Strict Mode
Add to composer.json:
"config": {
"platform-check": true,
"platform": {
"php": "8.1"
}
}
Ensures type safety during development.
Logging Edge Cases
try {
$result = Math::log(0);
} catch (\Exception $e) {
\Log::error("Math operation failed: " . $e->getMessage());
// Fallback logic
}
Testing Use PHPUnit to test edge cases:
public function testSafeDivideByZero()
{
$this->assertNull(Math::safeDivide(10, 0));
}
Custom Functions
Extend the Math class or create a decorator:
class ExtendedMath extends Math {
public static function taxAmount(float $amount, float $taxRate): float
{
return self::multiply($amount, self::divide($taxRate, 100));
}
}
Monkey-Patching (Not Recommended) Override methods in a service provider (use cautiously):
Math::divide = function ($a, $b) {
if ($b === 0) return null;
return $a / $b;
};
Laravel Service Container Bind custom math logic:
$this->app->extend('math', function ($app, $math) {
$math->setPrecision(4); // Hypothetical method
return $math;
});
Configuration
If the package supports config (e.g., config/math.php), customize:
'precision' => 6, // Default decimal places
'strict_mode' => true, // Enable strict type checks
How can I help you explore Laravel packages today?