tiny-blocks / money
Value Object that represents a monetary value.
Installs: 8 401
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 0
Forks: 0
Open Issues: 0
Requires
- php: ^8.1||^8.2
- tiny-blocks/currency: ^2.0
- tiny-blocks/math: ^2.0
- tiny-blocks/value-object: ^2.0
Requires (Dev)
- infection/infection: ^0.26
- phpmd/phpmd: ^2.13
- phpunit/phpunit: ^9.6
- squizlabs/php_codesniffer: ^3.7
Suggests
- ext-bcmath: Enables the extension which is an interface to the GNU implementation as a Basic Calculator utility library.
README
Overview
Value Object that represents a monetary value.
Installation
composer require tiny-blocks/money
How to use
The library exposes a concrete implementation for representing and performing monetary operations.
Using the from method
With the from
method, a new instance of type Money
is created from a valid numeric value. You can provide
a string
, float
or BigNumber
value.
Money::from(value: 10, currency: 'BRL'); Money::from(value: '10', currency: Currency::USD); Money::from(value: BigDecimal::from(value: '10'), currency: Currency::USD);
Floating point values instantiated from a float
may not be safe, as they are imprecise by design and may result in a
loss of precision. Always prefer to instantiate from a string
, which supports an unlimited amount digits.
Using the methods of mathematical operations
Addition
Performs an addition operation between this value and another value.
$augend = Money::from(value: '100', currency: 'BRL'); $addend = Money::from(value: '1.50', currency: Currency::BRL); $result = $augend->add(addend: $addend); $result->amount->toString(); # 101.50
Subtraction
Performs a subtraction operation between this value and another value.
$minuend = Money::from(value: '10.50', currency: 'EUR'); $subtrahend = Money::from(value: '0.50', currency: Currency::EUR); $result = $minuend->subtract(subtrahend: $subtrahend); $result->amount->toString(); # 10.00
Multiplication
Performs a multiplication operation between this value and another value.
$multiplicand = Money::from(value: '5', currency: 'GBP'); $multiplier = Money::from(value: '3.12', currency: Currency::GBP); $result = $multiplicand->multiply(multiplier: $multiplier); $result->amount->toString(); # 15.60
Division
Performs a division operation between this value and another value.
$dividend = Money::from(value: '8.99', currency: 'CHF'); $divisor = Money::from(value: '5', currency: Currency::CHF); $result = $dividend->divide(divisor: $divisor); $result->amount->toString(); # 1.79
License
Money is licensed under MIT.
Contributing
Please follow the contributing guidelines to contribute to the project.