Decimal value object for PHP.
https://php-collective.github.io/decimal-object/
Floats cannot represent most decimal fractions exactly, which makes them unsuitable for money and other values that must add up:
var_dump(0.1 + 0.2 === 0.3); // bool(false)Handling such values as strings works, and a value object keeps the logic for it in one place:
use PhpCollective\DecimalObject\Decimal;
$total = Decimal::create('0.1')->add('0.2');
echo $total; // 0.3
var_dump($total->equals('0.3')); // bool(true)- Explicit scale handling for arithmetic, truncation and rounding.
- Readable API:
add(),greaterThan(),isZero(). - Arithmetic, rounding, comparison and conversion.
- Immutable.
- Handles numbers beyond the integer and float range.
- Calculates with PHP's
bcmathextension.
Follow Installation to install the package and enable bcmath for the PHP process that runs it.
- dereuromark/cakephp-decimal as decimal type for the CakePHP ORM.
See Alternatives for how this library compares to php-decimal, brick/math and the money libraries.
Pull requests are welcome:
- Target
masterfor bug fixes and backwards compatible improvements. - Target
next(the next major version) for anything that breaks backwards compatibility.
The library was written in 2019 for the Spryker commerce framework and has been used there in order and price calculations since. This repository is the independently maintained continuation for the PHP ecosystem as a whole.