A PHP library providing immutable Money value object with arbitrary-precision and solution for floating point rounding errors.
What do you think will be printed in the example below?
print (36 - 35.99) === 0.01 ? 'β
equals' : 'not equals π';
Actually not equals π
. You can try https://ideone.com/2UQlBF.
Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.
-- Oracle
Install directly from command line using Composer
composer require fortis/moneyobject
$money = new Money(100, 'USF'); // throws InvalidCurrencyException
$money = Money::USD(100.20); // 100.20 USD. Short syntax with autocomplete.
$money = new Money(100.20, CurrencyCode::USD); // 100.20 USD
$money = Money::create(100.20, CurrencyCode::USD); // 100.20 USD
$money->getCurrency()->getCode(); // USD
$money->getAmount()->toFloat(); // 100.20
$money->multiply(2)
->getAmount()->toFloat(); // 200.40
$money->divide(Money::USD(2))
->getAmount()->toFloat(); // 50.10
$money->plus(Money::USD(2.5))
->getAmount()->toFloat(); // 102.70
$money->minus(Money::USD(0.5))
->getAmount()->toFloat(); // 99.70
Money::USD(36)->minus(Money::USD(35.99))
->getAmount()->toFloat(); // 0.01
Money::USD(36)->minus(35.99)
->getAmount()->toFloat(); // 0.01
$ composer require florianv/swap php-http/message php-http/guzzle6-adapter
$swap = (new SwapBuilder())
->add('fixer')
->build();
$converter = new Converter($swap);
$usd50 = Money::USD(50);
$result = $converter->convert($usd50, Currency::EUR());
moneyobject is licensed under the MIT license.