Skip to content

About

Decimal handling as value object instead of plain strings or floats.

Resources

Stars

24 stars

Watchers

1 watching

Forks

Repository files navigation

Decimal Object

CI codecov Latest Stable Version Minimum PHP Version PHPStan License

Decimal value object for PHP.

Documentation

https://php-collective.github.io/decimal-object/

Background

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)

Features

  • 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 bcmath extension.

Installation

Follow Installation to install the package and enable bcmath for the PHP process that runs it.

Usage

Integrations

See Alternatives for how this library compares to php-decimal, brick/math and the money libraries.

Contributing

Pull requests are welcome:

  • Target master for bug fixes and backwards compatible improvements.
  • Target next (the next major version) for anything that breaks backwards compatibility.

History

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.

About

Decimal handling as value object instead of plain strings or floats.

Resources

Stars

24 stars

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages