PHPackages                             yuwuhsien/laravel-bcmath-cast - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. yuwuhsien/laravel-bcmath-cast

ActiveLibrary[Database &amp; ORM](/categories/database)

yuwuhsien/laravel-bcmath-cast
=============================

Laravel Eloquent casts for PHP 8.4's BCMath\\Number object API, enabling natural operator-based arithmetic on model attributes while maintaining arbitrary precision decimal accuracy.

v1.1.0(5mo ago)2796—10%MITPHPPHP ^8.4CI passing

Since Nov 21Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/takeshiyu/laravel-bcmath-cast)[ Packagist](https://packagist.org/packages/yuwuhsien/laravel-bcmath-cast)[ RSS](/packages/yuwuhsien-laravel-bcmath-cast/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (9)Versions (3)Used By (0)

 [![Build Status](https://github.com/takeshiyu/laravel-bcmath-cast/actions/workflows/tests.yml/badge.svg)](https://github.com/takeshiyu/laravel-bcmath-cast/actions/workflows/tests.yml) [![Packagist Downloads](https://camo.githubusercontent.com/6b1424b4636c57b46415d0f902c1719a0d0b9068eaf0bc5657d8c435c6218ab1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f79757775687369656e2f6c61726176656c2d62636d6174682d63617374)](https://camo.githubusercontent.com/6b1424b4636c57b46415d0f902c1719a0d0b9068eaf0bc5657d8c435c6218ab1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f79757775687369656e2f6c61726176656c2d62636d6174682d63617374)

Laravel BCMath Cast
===================

[](#laravel-bcmath-cast)

Laravel Eloquent casts for PHP 8.4's `BCMath\Number` object API, enabling natural operator-based arithmetic on model attributes while maintaining arbitrary precision decimal accuracy.

Why This Package?
-----------------

[](#why-this-package)

PHP 8.4 introduced the `BCMath\Number` class with operator overloading, transforming cumbersome decimal calculations:

```
// Old way with BCMath functions
$total = bcadd(bcmul($price, $quantity), $tax, 2);

// New way with BCMath\Number
$total = ($price * $quantity) + $tax;
```

This package bridges Laravel's Eloquent ORM with PHP 8.4's BCMath\\Number, letting you write clean, precise arithmetic directly on model attributes.

Read more: [BCMath Object API in PHP 8.4](https://ywh.sh/writing/bcmath-object-api-in-php-84)

Requirements
------------

[](#requirements)

- **PHP 8.4+** (for `BCMath\Number` class)
- **Laravel 11.x**

Installation
------------

[](#installation)

```
composer require yuwuhsien/laravel-bcmath-cast
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

Add the `AsDecimal` cast to your Eloquent model:

```
use YuWuHsien\Decimal\Casts\AsDecimal;

class Product extends Model
{
    protected function casts(): array
    {
        return [
            'price' => AsDecimal::class,
            'cost' => AsDecimal::class,
            'tax_rate' => AsDecimal::class,
        ];
    }
}
```

Now your model attributes are automatically converted to `BCMath\Number` objects:

```
$product = Product::create([
    'price' => '19.99',
    'cost' => '12.50',
    'tax_rate' => '0.0825',
]);

// Attributes are BCMath\Number instances
$product->price instanceof Number; // true

// Perform precise calculations with natural operators
$margin = $product->price - $product->cost; // Number('7.49')
$marginPercent = ($margin / $product->cost) * new Number('100'); // Number('59.92')

// Calculate total with tax
$total = $product->price * (new Number('1') + $product->tax_rate); // Number('21.639175')
```

### Setting Values

[](#setting-values)

The cast accepts multiple input types:

```
// BCMath\Number objects
$product->price = new Number('29.99');

// Numeric strings (recommended for precision)
$product->price = '29.99';

// Integers
$product->price = 30;

// Floats (works but may lose precision - triggers warning)
$product->price = 29.99; // ⚠️ Warning: precision loss possible
```

### Database Column Types

[](#database-column-types)

**Use DECIMAL columns, NOT FLOAT:**

```
Schema::create('products', function (Blueprint $table) {
    $table->decimal('price', 10, 2);       // ✅ Correct
    $table->decimal('cost', 10, 4);        // ✅ Correct
    $table->float('amount');               // ❌ Wrong - loses precision
});
```

The DECIMAL type preserves exact decimal values. Floats introduce rounding errors that defeat the purpose of BCMath.

Testing
-------

[](#testing)

```
# Run tests
composer test

# Run tests with coverage
composer test-coverage

# Run static analysis
composer analyse
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance73

Regular maintenance activity

Popularity22

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

179d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3075c9103f3dddee28d255b45df7bfc4c58459e182f8c600a07930856e97dc39?d=identicon)[TakeshiYu](/maintainers/TakeshiYu)

---

Top Contributors

[![takeshiyu](https://avatars.githubusercontent.com/u/29810254?v=4)](https://github.com/takeshiyu "takeshiyu (7 commits)")

---

Tags

bcmathcastdecimaleloquentlaravelphp84precisionlaraveleloquentdecimalcastprecisionbcmathphp84

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/yuwuhsien-laravel-bcmath-cast/health.svg)

```
[![Health](https://phpackages.com/badges/yuwuhsien-laravel-bcmath-cast/health.svg)](https://phpackages.com/packages/yuwuhsien-laravel-bcmath-cast)
```

###  Alternatives

[silber/bouncer

Eloquent roles and abilities.

3.6k4.4M25](/packages/silber-bouncer)[watson/validating

Eloquent model validating trait.

9723.3M47](/packages/watson-validating)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[io238/laravel-iso-countries

Ready-to-use Laravel models and relations for country (ISO 3166), language (ISO 639-1), and currency (ISO 4217) information with multi-language support.

5462.3k](/packages/io238-laravel-iso-countries)[esensi/model

The base model traits of Esensi

20266.5k1](/packages/esensi-model)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
