search
HomeBackend DevelopmentPHP TutorialHandling Decimal Calculations in PHP with the New BCMath Object API

Handling Decimal Calculations in PHP  with the New BCMath Object API

Originally published at Takeshi Yu's Blog.


Accurate numerical computation is paramount in enterprise applications, especially those dealing with finance, accounting, or inventory. Even minor rounding errors can cause significant problems. PHP 8.4's enhanced BCMath Object API offers a refined solution for precise and efficient decimal calculations.


Experienced PHP developers are familiar with floating-point imprecision:

$a = 0.1;
$b = 0.2;
var_dump($a + $b);  // Outputs: 0.30000000000000004

This inaccuracy is unacceptable in financial contexts. These small errors accumulate, leading to real-world discrepancies.

Database Design for Precision

Precise decimal calculations begin with the database. The DECIMAL type is essential:

// In Laravel Migration
Schema::create('items', function (Blueprint $table) {
    $table->id();
    $table->decimal('quantity', 10, 3);  // Precision: 10 digits, 3 decimal places
    $table->decimal('price', 10, 3);     // Precision: 10 digits, 3 decimal places
    $table->decimal('discount', 10, 3);  // Precision: 10 digits, 3 decimal places
    $table->decimal('tax', 10, 3);       // Precision: 10 digits, 3 decimal places
    // ... other columns
});

DECIMAL ensures:

  • Exact decimal precision.
  • Customizable scale and precision.
  • Suitability for financial applications.

While potentially slightly slower than FLOAT, the precision advantage outweighs the performance difference in mission-critical systems.

Leveraging Laravel's Casting

Laravel simplifies decimal handling with its casting system:

class Item extends Model
{
    protected $casts = [
        'quantity' => 'decimal:3',
        'price' => 'decimal:3',
        'discount' => 'decimal:3',
        'tax' => 'decimal:3',
    ];
}

However, remember that Laravel casting primarily manages:

  • Data formatting.
  • Consistent value representation.

Avoiding Type Conversion Pitfalls

Even with correct database types and Laravel casting, calculation errors can occur:

// Database values
$item1 = Item::find(1);  // price: "99.99"
$item2 = Item::find(2);  // price: "149.99"

// Calculation without BCMath
$subtotal = $item1->price + $item2->price;
$tax = $subtotal * 0.05;  // 5% tax

var_dump($tax);  // Outputs: float(12.499000000000002) instead of 12.499

This happens because PHP implicitly converts strings to numbers during arithmetic:

// String values from database
$price1 = "99.99";
$price2 = "149.99";
echo gettype($price1);  // string

// Implicit conversion to float
$total = $price1 + $price2;
echo gettype($total);   // double (float)

BCMath Before PHP 8.4: Precise but Tedious

The traditional BCMath extension provides precision:

// Database values
$item1 = Item::find(1);  // price: "99.99"
$item2 = Item::find(2);  // price: "149.99"

// Using BCMath functions
$subtotal = bcadd($item1->price, $item2->price, 3);
$tax = bcmul($subtotal, $item2->tax, 3);

var_dump($tax);  // Precisely outputs: string(5) "12.499"

However, complex calculations become verbose and less maintainable:

// Complex order calculation (using BCMath functions)
// ... (code omitted for brevity)

PHP 8.4's BCMath Object API: Elegance and Precision

PHP 8.4's object-oriented BCMath API simplifies precise calculations:

use BCMath\Number;

$item1 = Item::find(1);
$price = new Number($item1->price);
$quantity = new Number($item1->quantity);
$discountRate = new Number($item1->discount);
$taxRate = new Number($item1->tax);

// Natural and readable calculations
$subtotal = $price * $quantity;
$discount = $subtotal * $discountRate;
$afterDiscount = $subtotal - $discount;
$tax = $afterDiscount * $taxRate;
$total = $afterDiscount + $tax;

var_dump($total);  // Automatically converts to string

Advantages of the new API:

  • Intuitive object-oriented design.
  • Standard mathematical operator support.
  • Immutable objects for data integrity.
  • Stringable interface implementation.

Seamless Laravel Integration

Further elegance is achieved with Laravel's accessors:

use BCMath\Number;

class Item extends Model
{
    // ... (accessor methods for quantity, price, discount, tax using Number) ...
}

Or with a custom cast:

// ... (DecimalCast class implementation) ...

Then:

$item1 = Item::find(1);

$subtotal = $item1->price * $item1->quantity;
// ... (rest of the calculation) ...

Conclusion

In healthcare inventory management, precise decimal calculations are vital. PHP 8.4's BCMath Object API, integrated with Laravel, significantly improves the handling of these calculations, offering precision, readability, maintainability, and type safety. While the older BCMath functions served their purpose, this new approach streamlines development considerably.

The above is the detailed content of Handling Decimal Calculations in PHP with the New BCMath Object API. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)