3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 use Brick\Money\Money
;
19 use Brick\Money\Context\DefaultContext
;
20 use Brick\Money\Context\CustomContext
;
21 use Brick\Math\RoundingMode
;
26 class CRM_Utils_Money
{
27 public static $_currencySymbols = NULL;
30 * Format a monetary string.
32 * Format a monetary string basing on the amount provided,
33 * ISO currency code provided and a format string consisting of:
35 * %a - the formatted amount
36 * %C - the currency ISO code (e.g., 'USD') if provided
37 * %c - the currency symbol (e.g., '$') if available
39 * @param float $amount
40 * The monetary amount to display (1234.56).
41 * @param string $currency
42 * The three-letter ISO currency code ('USD').
43 * @param string $format
44 * The desired currency format.
45 * @param bool $onlyNumber
48 * formatted monetary string
51 public static function format($amount, $currency = NULL, $format = NULL, $onlyNumber = FALSE) {
53 if (CRM_Utils_System
::isNull($amount)) {
57 $config = CRM_Core_Config
::singleton();
60 $format = $config->moneyformat
;
64 $currency = $config->defaultCurrency
;
68 $amount = self
::formatLocaleNumericRoundedByCurrency($amount, $currency);
72 if (!self
::$_currencySymbols) {
73 self
::$_currencySymbols = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'currency', [
74 'keyColumn' => 'name',
75 'labelColumn' => 'symbol',
79 // ensure $currency is a valid currency code
80 // for backwards-compatibility, also accept one space instead of a currency
81 if ($currency != ' ' && !array_key_exists($currency, self
::$_currencySymbols)) {
82 throw new CRM_Core_Exception("Invalid currency \"{$currency}\"");
85 if ($currency === ' ') {
86 CRM_Core_Error
::deprecatedWarning('Passing empty currency to CRM_Utils_Money::format is deprecated if you need it for display without currency call CRM_Utils_Money::formatLocaleNumericRounded');
89 $amount = self
::formatNumericByFormat($amount);
90 // If it contains tags, means that HTML was passed and the
91 // amount is already converted properly,
92 // so don't mess with it again.
93 // @todo deprecate handling for the html tags because .... WTF
94 if (strpos($amount, '<') === FALSE) {
95 $amount = self
::replaceCurrencySeparators($amount);
101 '%c' => CRM_Utils_Array
::value($currency, self
::$_currencySymbols, $currency),
103 return strtr($format, $replacements);
107 * This is a placeholder function for calculating the number of decimal places for a currency.
109 * Currently code assumes 2 decimal places but some currencies (bitcoin, middle eastern) have
110 * more. By using this function we can signpost the locations where the number of decimal places is
111 * currency specific for future enhancement.
113 * @param string $currency
116 * Number of decimal places.
118 public static function getCurrencyPrecision($currency = NULL) {
123 * Subtract currencies using integers instead of floats, to preserve precision
125 * @param string|float $leftOp
126 * @param string|float $rightOp
127 * @param string $currency
130 * Result of subtracting $rightOp from $leftOp to the precision of $currency
132 public static function subtractCurrencies($leftOp, $rightOp, $currency) {
133 if (is_numeric($leftOp) && is_numeric($rightOp)) {
134 $leftMoney = Money
::of($leftOp, $currency, new DefaultContext(), RoundingMode
::CEILING
);
135 $rightMoney = Money
::of($rightOp, $currency, new DefaultContext(), RoundingMode
::CEILING
);
136 return $leftMoney->minus($rightMoney)->getAmount()->toFloat();
141 * Tests if two currency values are equal, taking into account the currency's
142 * precision, so that the two values are compared as integers after rounding.
146 * 1.231 == 1.232 with a currency precision of 2 decimal points
147 * 1.234 != 1.236 with a currency precision of 2 decimal points
148 * 1.300 != 1.200 with a currency precision of 2 decimal points
156 public static function equals($value1, $value2, $currency) {
157 $precision = pow(10, self
::getCurrencyPrecision($currency));
159 return (int) round($value1 * $precision) == (int) round($value2 * $precision);
163 * Format money for display (just numeric part) according to the current locale.
165 * This calls the underlying system function but does not handle currency separators.
167 * It's not totally clear when it changes the $amount value but has historical usage.
173 protected static function formatLocaleNumeric($amount) {
174 return self
::formatNumericByFormat($amount);
178 * Format money for display (just numeric part) according to the current locale with rounding.
180 * At this stage this is conceived as an internal function with the currency wrapper
181 * functions determining the number of places.
183 * This calls the underlying system function but does not handle currency separators.
185 * It's not totally clear when it changes the $amount value but has historical usage.
187 * @param string $amount
188 * @param int $numberOfPlaces
192 protected static function formatLocaleNumericRounded($amount, $numberOfPlaces) {
193 if (!extension_loaded('intl')) {
194 self
::missingIntlNotice();
195 return self
::formatNumericByFormat($amount, '%!.' . $numberOfPlaces . 'i');
197 $money = Money
::of($amount, CRM_Core_Config
::singleton()->defaultCurrency
, new CustomContext($numberOfPlaces), RoundingMode
::CEILING
);
198 // @todo - we specify en_US here because we don't want this function to do
199 // currency replacement at the moment because
200 // formatLocaleNumericRoundedByPrecision is doing it and if it
201 // is done there then it is swapped back in there.. This is a short term
202 // fix to allow us to resolve formatLocaleNumericRoundedByPrecision
203 // and to make the function comments correct - but, we need to reconsider this
204 // in master as it is probably better to use locale than our currency separator fields.
205 $formatter = new \
NumberFormatter('en_US', NumberFormatter
::DECIMAL
);
206 $formatter->setAttribute(\NumberFormatter
::MIN_FRACTION_DIGITS
, $numberOfPlaces);
207 return $money->formatWith($formatter);
211 * Format money for display (just numeric part) according to the current locale with rounding.
213 * This handles both rounding & replacement of the currency separators for the locale.
215 * @param string $amount
216 * @param string $currency
221 public static function formatLocaleNumericRoundedByCurrency($amount, $currency) {
222 return self
::formatLocaleNumericRoundedByPrecision($amount, self
::getCurrencyPrecision($currency));
226 * Format money for display (just numeric part) according to the current locale with rounding to the supplied precision.
228 * This handles both rounding & replacement of the currency separators for the locale.
230 * @param string $amount
231 * @param int $precision
236 public static function formatLocaleNumericRoundedByPrecision($amount, $precision) {
237 $amount = self
::formatLocaleNumericRounded($amount, $precision);
238 return self
::replaceCurrencySeparators($amount);
242 * Format money for display with rounding to the supplied precision but without padding.
244 * If the string is shorter than the precision trailing zeros are not added to reach the precision
245 * beyond the 2 required for normally currency formatting.
247 * This handles both rounding & replacement of the currency separators for the locale.
249 * @param string $amount
250 * @param int $precision
255 public static function formatLocaleNumericRoundedByOptionalPrecision($amount, $precision) {
256 $decimalPlaces = strlen(substr($amount, strpos($amount, '.') +
1));
257 $amount = self
::formatLocaleNumericRounded($amount, $precision > $decimalPlaces ?
$decimalPlaces : $precision);
258 return self
::replaceCurrencySeparators($amount);
262 * Format money for display (just numeric part) according to the current locale with rounding based on the
263 * default currency for the site.
268 public static function formatLocaleNumericRoundedForDefaultCurrency($amount) {
269 return self
::formatLocaleNumericRoundedByCurrency($amount, self
::getCurrencyPrecision(CRM_Core_Config
::singleton()->defaultCurrency
));
273 * Replace currency separators.
275 * @param string $amount
279 protected static function replaceCurrencySeparators($amount) {
280 $config = CRM_Core_Config
::singleton();
282 ',' => $config->monetaryThousandSeparator
,
283 '.' => $config->monetaryDecimalPoint
,
285 return strtr($amount, $rep);
289 * Format numeric part of currency by the passed in format.
291 * This is envisaged as an internal function, with wrapper functions defining valueFormat
292 * into easily understood functions / variables and handling separator conversions and
295 * @param string $amount
296 * @param string $valueFormat
300 protected static function formatNumericByFormat($amount, $valueFormat = '%!i') {
301 // money_format() exists only in certain PHP install (CRM-650)
302 // setlocale() affects native gettext (CRM-11054, CRM-9976)
303 if (is_numeric($amount) && function_exists('money_format')) {
304 $lc = setlocale(LC_MONETARY
, 0);
305 setlocale(LC_MONETARY
, 'en_US.utf8', 'en_US', 'en_US.utf8', 'en_US', 'C');
306 $amount = money_format($valueFormat, $amount);
307 setlocale(LC_MONETARY
, $lc);
313 * Emits a notice indicating we have fallen back to a less accurate way of formatting money due to missing intl extension
315 public static function missingIntlNotice() {
316 CRM_Core_Session
::singleton()->setStatus(ts('As this system does not include the PHP intl extension, CiviCRM has fallen back onto a slightly less accurate and deprecated method to format money'), ts('Missing PHP INTL extension'));