oriolsegura/laravel-decimal 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

oriolsegura/laravel-decimal

Composer 安装命令:

composer require oriolsegura/laravel-decimal

包简介

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

README 文档

README

Latest Version on Packagist Tests Total Downloads License PHP Version

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

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

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

Featured on Laravel News.

Quality & Correctness Pipeline

⚠️ 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

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

Installation

composer require oriolsegura/laravel-decimal

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, // <-- Automatic casting
    ];
}


// Enjoy seamless precision!

$product = Product::create([
    'price' => '19.99',
]);

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

Usage Highlights

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)
              ->times(2);

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

Laravel Decimal includes a robust, zero-dependency mathematical expression parser based on the 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 & 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

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)
  • roundUp(int $scale = 0)

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

License

This package is open-sourced software licensed under the MIT license.

oriolsegura/laravel-decimal 适用场景与选型建议

oriolsegura/laravel-decimal 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 12 次下载、GitHub Stars 达 4, 最近一次更新时间为 2026 年 02 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「money」 「decimal」 「laravel」 「precision」 「eloquent」 「cast」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 oriolsegura/laravel-decimal 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 oriolsegura/laravel-decimal 我们能提供哪些服务?
定制开发 / 二次开发

基于 oriolsegura/laravel-decimal 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 12
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 5
  • 点击次数: 33
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 4
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-02-05