thedevick / precise-money
Manipulate money precisely with PHP.
Requires
- ext-bcmath: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.21
- phpunit/phpunit: ^10.2
- symfony/var-dumper: ^6.2
- vimeo/psalm: ^5.13
README
The Money Object
The Money class is an immutable class, that represent an amount of money. You can add, subtract, multiply and divide the amount in the object with numeric-string or other Money object. Also, the Money Class is Json Serializable and Stringable.
<?php use TheDevick\PreciseMoney\Calculator\BCMathCalculator; use TheDevick\PreciseMoney\Money; $money = new Money('10', new BCMathCalculator(3)); // Start with $10.000, using the BCMathCalculator with scale 3 (The default is using scale 10) $money = $money->addMoney(new Money('3')); // Add $3.000 $money = $money->add('5.235'); // Add $5.235 return json_encode($money); // Returns {"amount":"18.235"}
Internally
Internally, the Money object stores the amount in an numeric-string.
Why use Precise Money?
This package provides an way to calculate money precisely. In other libraries,that stores the amount as cents as an integer,you can't calculate, for example, the price per kWh, since the price per kWh usally have more than 4 decimals. But since the Precise Money package stores the amount as an numeric-string, you can store many decimals as you wan't.
Calculating
Today, we only have the BCMathCalculator
available, that implements the CalculatorInterface
.
Tests
Calculator
To test calculator classes that implements the Calculator Interface, you can use the Calculator Test Trait. It have some methods that can help you write your tests:
generateCalculatorMessage(CalculatorInterface $calculator)
Returns a nice message that says the Class and Scale of the Calculator. Useful with$message
argument in assertions.assertCalculatorAddMethod($calculator, $expected, $x, $y)
This methods asserts the calculator add method.assertCalculatorAddMethodComplete($calculator)
nThis methods asserts many operations with the calculator.