Money
Money
The Hazaar\Util\Money class simplifies working with currency values. It provides features for:
- Formatting money values based on locale.
- Converting values between different currencies.
- Performing arithmetic operations (addition, subtraction) on money objects, even with different currencies.
Getting Started
To generic usage involves instantiating the Money class with a value and an optional currency code.
use Hazaar\Util\Money;
$price = new Money(19.95, 'USD');If no currency is specified, the class attempts to determine the default currency from the system locale. You can also explicitly set a default currency.
Configuration
You can set the default currency globally for your application. This is typically done in your bootstrap.php file.
use Hazaar\Util\Money;
Money::setDefaultCurrency('AUD');With this set, new Money instances will default to Australian Dollars if no currency is provided.
$amount = new Money(50); // Defaults to AUDCurrency Conversion
The Money class uses the Hazaar API reference to perform real-time currency conversions. Exchange rates are cached to ensure performance.
Info
Currency information is downloaded from the Hazaar API server at api.hazaar.io. Data is refreshed every few hours and cached locally. As such, this service should not be relied upon for up-to-the-second accurate currency conversion and rate information.
To convert a value to another currency:
$usd = new Money(100, 'USD');
$aud = $usd->convertTo('AUD');
echo $aud->format(); // Outputs something like 50.00AUD (depending on rate)Arithmetic Operations
You can add or subtract money objects. If the currencies differ, the value being added/subtracted is automatically converted to the base object's currency before the operation.
Addition
$val1 = new Money(100, 'USD');
$val2 = new Money(100, 'AUD');
// Adds the converted value of 100 AUD to 100 USD
$total = $val1->add($val2);
echo $total->getCurrencyCode(); // USDSubtraction
$val1 = new Money(200, 'USD');
$val2 = new Money(50, 'USD');
$result = $val1->subtract($val2);Formatting and Output
You can output the money value as a string, which formats it according to international standards (e.g., Symbol + Amount + Code).
$money = new Money(1234.56, 'USD');
echo $money->toString(); // e.g., ,234.56USD
echo $money; // Same as toString()To get the raw value types:
echo $money->toFloat(); // 1234.56
echo $money->toCents(); // 123456Currency Information
The class provides methods to retrieve currency details.
$money = new Money(100, 'JPY');
echo $money->getCurrencyName(); // Yen
echo $money->getCurrencySymbol(); // ¥
echo $money->getCurrencyCode(); // JPY