PHPackages                             oriolsegura/laravel-decimal - 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. oriolsegura/laravel-decimal

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

oriolsegura/laravel-decimal
===========================

Value Object to handle decimals in Laravel without losing precision and directly from Eloquent models.

v0.11.1(4w ago)5211MITPHPPHP ^8.2CI passing

Since Feb 5Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/oriolsegura/laravel-decimal)[ Packagist](https://packagist.org/packages/oriolsegura/laravel-decimal)[ RSS](/packages/oriolsegura-laravel-decimal/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (27)Versions (19)Used By (0)

Laravel Decimal
===============

[](#laravel-decimal)

[![Latest Version on Packagist](https://camo.githubusercontent.com/aa8bbaa1dfa424be256e977e77979706a5fde971f6042153c0865d4fdb95f97b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f72696f6c7365677572612f6c61726176656c2d646563696d616c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/oriolsegura/laravel-decimal)[![Tests](https://camo.githubusercontent.com/fc05f08c8e63c6005ec6e9b0f15d2d35ab3ed7ae8c31a6413a481b2fd386692f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6f72696f6c7365677572612f6c61726176656c2d646563696d616c2f74657374732e796d6c3f6272616e63683d6d6173746572266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/oriolsegura/laravel-decimal/actions)[![Total Downloads](https://camo.githubusercontent.com/bd48e2f893f58003f966340c8d9d3005755b3a038f7baa873e3dd83d3a0d2432/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f72696f6c7365677572612f6c61726176656c2d646563696d616c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/oriolsegura/laravel-decimal)[![License](https://camo.githubusercontent.com/b570a6dc9868d7c4a5972f8ffd501bf25dbfbfa3c0361739c4e0567c3d730609/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6f72696f6c7365677572612f6c61726176656c2d646563696d616c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/oriolsegura/laravel-decimal)[![PHP Version](https://camo.githubusercontent.com/10413ad9d9bcc0609ebaa03607fd4dbf3f9eeab1791a3b8e31453985463b38e1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6f72696f6c7365677572612f6c61726176656c2d646563696d616c3f7374796c653d666c61742d737175617265)](https://packagist.org/packages/oriolsegura/laravel-decimal)

**A lightweight, immutable Value Object for high-precision decimal arithmetic in Laravel.**

Uses `bcmath` internally to guarantee numerical correctness — essential for financial applications where floating-point errors are unacceptable.

🚀 Why This Package Matters
--------------------------

[](#-why-this-package-matters)

Floating-point arithmetic is fundamentally imprecise. This library solves that problem cleanly:

- **Financial-grade precision**: Perfect for money, pricing, accounting, and market data.
- **Immutable &amp; Type-Safe**: Designed with Value Object principles in mind.
- **Production-focused**: Built with rigorous quality practices.

Featured on [Laravel News](https://laravel-news.com).

### Quality &amp; Correctness Pipeline

[](#quality--correctness-pipeline)

- **Mutation Testing** with [Infection](https://github.com/infection/infection).

⚠️ The Problem with Floats
--------------------------

[](#️-the-problem-with-floats)

Floating-point arithmetic is not precise because IEEE 754 standard cannot represent all decimal fractions exactly.

Some examples of this issue:

```
echo sprintf("%.17f", 0.1 + 0.2); // 0.30000000000000004 ❌

echo var_dump(0.3 === (0.1 + 0.2)); // bool(false) ❌
```

🛠️ Requirements
---------------

[](#️-requirements)

- PHP 8.2+
- Laravel 11.0+ / 12.0+ / 13.0+
- `ext-bcmath`

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

[](#installation)

```
composer require oriolsegura/laravel-decimal
```

Eloquent Integration
--------------------

[](#eloquent-integration)

This package shines when used with Eloquent models. You can store values as precise decimals (or strings) in your database and work with Decimal objects automatically in your code.

```
use Illuminate\Database\Eloquent\Model;
use OriolSegura\Decimal\Decimal;

class Product extends Model
{
    protected $casts = [
        'price' => Decimal::class, //  '19.99',
]);

$product->price = $product->price->add('5.50');
$product->save();
```

Usage Highlights
----------------

[](#usage-highlights)

### Creation &amp; Arithmetic

[](#creation--arithmetic)

You can create a Decimal from a string, integer or another Decimal.

```
$val = Decimal::from('10.50');

$result = $val->plus('5.50')
              ->minus(2)  // you could also use the string "2" but using integers when
              ->times(2); // possible is a good practice because they are parsed faster

echo $val; // "10.50" (original value remains unchanged)
echo $result; // "28.00" (new Decimal instance with the result)
```

Additionally, a `Decimal::zero()` static method is available for convenience.

### Safe Expression Evaluator

[](#safe-expression-evaluator)

Laravel Decimal includes a robust, zero-dependency mathematical expression parser based on the [Shunting yard algorithm](https://en.wikipedia.org/wiki/Shunting_yard_algorithm).

```
echo Decimal::resolve('(10.5 + 2) * -1.5 / 2'); // '-9.375'
```

Thanks to the `__toString()` implementation, you can even interpolate existing Decimal instances directly into your expression strings for ultimate readability:

```
$base    = Decimal::from('100');
$taxRate = Decimal::from('0.21');

echo Decimal::resolve("$base + ($base * $taxRate)"); // '121'
```

### Division &amp; Rounding

[](#division--rounding)

By default, division uses an automatic scale equal to the maximum of the two operands scales, ensuring this is also at least 12 decimal places to ensure precision. But you can also provide a `$scale` parameter to specify the number of decimal places in the result.

```
echo Decimal::from(2)->div(3, scale: 2); // "0.67"
```

### All Supported Methods

[](#all-supported-methods)

These are the implemented methods for arithmetic operations:

- `plus(self|int|string $other, self|int|string ...$others)` (aliases: `add`, `sum`)
- `minus(self|int|string $other)` (aliases: `take`, `subtract`)
- `times(self|int|string $other, self|int|string ...$others)` (aliases: `mul`, `multiply`)
- `dividedBy(self|int|string $other, int|null $scale = null)` (alias: `div`)
- `inverse(null|int $scale = null)` (aliases: `inv`, `reciprocal`)
- `mod(self|int|string $other)` (aliases: `modulo`, `remainder`)
- `negate()` (alias: `neg`)
- `abs()`

And these are the implemented methods for comparisons:

- `cmp(self|int|string $other)` (alias: `compare`)
- `eq(self|int|string $other)` (alias: `equals`)
- `ne(self|int|string $other)` (aliases: `notEquals`, `diff`)
- `gt(self|int|string $other)` (alias: `greaterThan`)
- `gte(self|int|string $other)` (alias: `greaterThanOrEqual`)
- `lt(self|int|string $other)` (alias: `lessThan`)
- `lte(self|int|string $other)` (alias: `lessThanOrEqual`)
- `isZero()`
- `isPositive()`
- `isNegative()`
- `isStrictlyPositive()`
- `isStrictlyNegative()`
- static: `min(self|int|string $other, self|int|string ...$values)`
- static: `max(self|int|string $other, self|int|string ...$values)`

Support is also given for truncation and rounding:

- `truncate(int $scale = 0)` (alias: `floor`)
- `round(int $scale = 0)`
- `roundUp(int $scale = 0)` (alias: `ceil`)

### Operate with Collections

[](#operate-with-collections)

Both the sum and multiplication methods leverage PHP's variadic arguments, making them incredibly easy to apply to collections:

```
$sum = $initial->sum(...$collection->pluck('value'));
// or if no initial value is needed:
$sum = Decimal::zero()->sum(...$collection->pluck('value'));
```

This clean syntax completely replaces the traditional, much more verbose `reduce` pattern:

```
$sum = $collection->reduce(function (Decimal $carry, $item): Decimal {
    return $carry->plus($item->value);
}, initial: $initial);
```

Which can be even simpler thanks to the helper function:

```
use function OriolSegura\sum;
$sum = sum(...$collection->pluck('value'));
$sum = sum(...$collection->pluck('value'), initial: 64);
```

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance88

Actively maintained with recent releases

Popularity14

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity46

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 ~10 days

Recently: every ~16 days

Total

17

Last Release

28d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/62751423?v=4)[Oriol Segura](/maintainers/oriolsegura)[@oriolsegura](https://github.com/oriolsegura)

---

Top Contributors

[![oriolsegura](https://avatars.githubusercontent.com/u/62751423?v=4)](https://github.com/oriolsegura "oriolsegura (24 commits)")

---

Tags

bcmathdecimaleloquent-castfloating-pointlaravelmoneyphpprecisionvalue-objectlaravelmoneyValue Objecteloquentdecimalcastprecision

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/oriolsegura-laravel-decimal/health.svg)

```
[![Health](https://phpackages.com/badges/oriolsegura-laravel-decimal/health.svg)](https://phpackages.com/packages/oriolsegura-laravel-decimal)
```

###  Alternatives

[spatie/laravel-permission

Permission handling for Laravel 12 and up

13.0k107.5M1.6k](/packages/spatie-laravel-permission)[psalm/plugin-laravel

Psalm plugin for Laravel

3345.4M354](/packages/psalm-plugin-laravel)[laravel/ai

The official AI SDK for Laravel.

1.1k4.6M323](/packages/laravel-ai)[watson/validating

Eloquent model validating trait.

9733.6M55](/packages/watson-validating)[bavix/laravel-wallet

It's easy to work with a virtual wallet.

1.3k1.4M21](/packages/bavix-laravel-wallet)[api-platform/laravel

API Platform support for Laravel

58190.1k21](/packages/api-platform-laravel)

PHPackages © 2026

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