A basic example implementation of the Fowler's Money pattern. The library performs money operations using the currency's smallest unit to prevent rounding errors.
<?php
use Money;
$euro = Money::eur(100);
$tenEuro = $euro + Money::eur(900);
print($tenEuro->format()); // 10,00 €
$shares = $tenEuro->allocate([1,1,1]);
print($shares[0]->format()); //3,34 €
print($shares[1]->format()); //3,33 €
print($shares[2]->format()); //3,33 €
Money amount is represented in currency's smallest units / cents. (e.g. 100 for 1 euro).
$euro = Money::eur(100);
print($euro->getAmount()); // 100
-
add
-
subtract
-
multiply
-
divide
Sum amount of two money objects using the add
method. Addition must be made between objects with the same currency.
$fiveEuro = Money::eur(500);
$tenEuro = $fiveEuro->add($fiveEuro);
Subtract amount of two money objects using the subtract
. Subtraction must be made between objects with the same currency.
$fiveEuro = Money::eur(500);
$zeroEuro = $fiveEuro->subtract($fiveEuro);
Multiply amount using the multiply
method.
$fiveEuro = Money::eur(500);
$tenEuro = $fiveEuro->multiply(2);
Divide amount using the divide
method.
$tenEuro = Money::eur(500);
$fiveEuro = $tenEuro->divide(2);
- Allocate
Split money amount according to provided ratios. Remaining amount is distributed to shares with the biggest ratios.
$tenEuro = Money::eur(1000);
$shares = $tenEuro->allocate([1,1,1]);
print($shares[0]->getAmount()); //334
print($shares[1]->getAmount()); //333
print($shares[2]->getAmount()); //333
Compare two money objects using the equals
method. The method will return false when amount or currency type is the same.
$tenEuro = Money::eur(1000);
$oneEuro = Money::eur(100);
$oneDollar = Money::usd(100);
$oneEuro->equals($tenEuro); // false
$oneEuro->equals($oneDollar); // false
Check if money amount is larger than the given money amount using the greaterThan
method.
$tenEuro = Money::eur(1000);
$oneEuro = Money::eur(100);
$tenEuro->greaterThan($oneEuro); // true
Check if money amount is larger or equal to the given money amount using the greaterThanOrEqual
method.
$oneEuro = Money::eur(100);
$oneEuro->greaterThanOrEqual($oneEuro); // true
Check if money amount is less than the given money amount using the lessThan
method.
$tenEuro = Money::eur(1000);
$oneEuro = Money::eur(100);
$oneEuro->lessThan($tenEuro); // true
Check if money amount is lessor equal to the given money amount using the lessThanOrEqual
method.
$oneEuro = Money::eur(100);
$oneEuro->lessThanOrEqual($oneEuro); // true
Format the money using the format
method.
$oneEuro = Money::eur(100);
print($oneEuro->format()); // 1,00 €
phpunit
The MIT License (MIT). See the license file for more information.