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.8.0(1mo ago)43MITPHPPHP ^8.2CI passing

Since Feb 5Pushed 1mo agoCompare

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

READMEChangelogDependencies (9)Versions (13)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 to handle decimals in Laravel without losing precision.

It uses `bcmath` internally to ensure mathematical correctness where floats fail.

🚀 Why use this package?
-----------------------

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

Designed for **simplicity and immediate productivity**. If you need to handle money or precise numbers in Laravel but don't want the overhead of heavy financial libraries or complex configurations, this is for you.

- **Plug &amp; Play:** Zero configuration. Works out of the box.
- **Laravel Native:** Built with Eloquent casting in mind.
- **Lightweight:** No heavy dependencies. Just a wrapper around `bcmath`.

Ideal for e-commerce, invoices, scientific data, and any scenario where `0.1 + 0.2` **must** equal `0.3`.

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

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

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

An example 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 Casting
----------------

[](#eloquent-casting)

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.

1. Define the cast in your Model:

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

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

// You can operate directly on the attribute
$product->price = $product->price->add('5.50');
$product->save();
```

Usage API
---------

[](#usage-api)

### Creation

[](#creation)

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

```
$a = Decimal::from('10.50');
$b = Decimal::from(10);
```

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

### Arithmetic

[](#arithmetic)

Since the object is immutable, operations always return a new instance.

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

// Chaining
$result = $val->plus(5)->minus(2)->times(2); // (10 + 5 - 2) * 2 = 26
```

### Supported methods

[](#supported-methods)

These are the implemented methods for arithmetic operations:

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

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)` (alias: `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()`
- `min(self|int|string $other, self|int|string ...$values)`
- `max(self|int|string $other, self|int|string ...$values)`

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.

Currently, this library only supports Half-Up Rounding for division.

```
// Automatic scale (truncating logic for infinite fractions)
echo Decimal::from(1)->div(3); // "0.333333333333"

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

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). It respects order of operations, nested parentheses, and handles unary negative numbers safely.

```
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'
```

License
-------

[](#license)

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

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance92

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

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

Recently: every ~13 days

Total

11

Last Release

39d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/09e4ff69aa5d1af5486dcb4280bfb3eb335110fd99e6d7168066cc0d19269a35?d=identicon)[oriolsegura](/maintainers/oriolsegura)

---

Top Contributors

[![oriolsegura](https://avatars.githubusercontent.com/u/62751423?v=4)](https://github.com/oriolsegura "oriolsegura (20 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

[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)
