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
46 * @param string $valueFormat
47 * The desired monetary value display format (e.g. '%!i').
50 * formatted monetary string
53 public static function format($amount, $currency = NULL, $format = NULL, $onlyNumber = FALSE, $valueFormat = NULL) {
55 if (CRM_Utils_System
::isNull($amount)) {
59 $config = CRM_Core_Config
::singleton();
62 $format = $config->moneyformat
;
66 $valueFormat = $config->moneyvalueformat
;
69 if (!empty($valueFormat) && $valueFormat !== '%!i') {
70 CRM_Core_Error
::deprecatedFunctionWarning('Having a Money Value format other than !%i is deprecated, please report this on the GitLab Issue https://lab.civicrm.org/dev/core/-/issues/1494 with the relevant moneyValueFormat you use.');
74 // money_format() exists only in certain PHP install (CRM-650)
75 if (is_numeric($amount) and function_exists('money_format')) {
76 $amount = money_format($valueFormat, $amount);
81 if (!self
::$_currencySymbols) {
82 self
::$_currencySymbols = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'currency', [
83 'keyColumn' => 'name',
84 'labelColumn' => 'symbol',
89 $currency = $config->defaultCurrency
;
92 // ensure $currency is a valid currency code
93 // for backwards-compatibility, also accept one space instead of a currency
94 if ($currency != ' ' && !array_key_exists($currency, self
::$_currencySymbols)) {
95 throw new CRM_Core_Exception("Invalid currency \"{$currency}\"");
98 $amount = self
::formatNumericByFormat($amount, $valueFormat);
99 // If it contains tags, means that HTML was passed and the
100 // amount is already converted properly,
101 // so don't mess with it again.
102 // @todo deprecate handling for the html tags because .... WTF
103 if (strpos($amount, '<') === FALSE) {
104 $amount = self
::replaceCurrencySeparators($amount);
110 '%c' => CRM_Utils_Array
::value($currency, self
::$_currencySymbols, $currency),
112 return strtr($format, $replacements);
116 * This is a placeholder function for calculating the number of decimal places for a currency.
118 * Currently code assumes 2 decimal places but some currencies (bitcoin, middle eastern) have
119 * more. By using this function we can signpost the locations where the number of decimal places is
120 * currency specific for future enhancement.
122 * @param string $currency
125 * Number of decimal places.
127 public static function getCurrencyPrecision($currency = NULL) {
132 * Subtract currencies using integers instead of floats, to preserve precision
134 * @param string|float $leftOp
135 * @param string|float $rightOp
136 * @param string $currency
139 * Result of subtracting $rightOp from $leftOp to the precision of $currency
141 public static function subtractCurrencies($leftOp, $rightOp, $currency) {
142 if (is_numeric($leftOp) && is_numeric($rightOp)) {
143 $leftMoney = Money
::of($leftOp, $currency, new DefaultContext(), RoundingMode
::CEILING
);
144 $rightMoney = Money
::of($rightOp, $currency, new DefaultContext(), RoundingMode
::CEILING
);
145 return $leftMoney->minus($rightMoney)->getAmount()->toFloat();
150 * Tests if two currency values are equal, taking into account the currency's
151 * precision, so that the two values are compared as integers after rounding.
155 * 1.231 == 1.232 with a currency precision of 2 decimal points
156 * 1.234 != 1.236 with a currency precision of 2 decimal points
157 * 1.300 != 1.200 with a currency precision of 2 decimal points
165 public static function equals($value1, $value2, $currency) {
166 $precision = pow(10, self
::getCurrencyPrecision($currency));
168 return (int) round($value1 * $precision) == (int) round($value2 * $precision);
172 * Format money for display (just numeric part) according to the current locale.
174 * This calls the underlying system function but does not handle currency separators.
176 * It's not totally clear when it changes the $amount value but has historical usage.
182 protected static function formatLocaleNumeric($amount) {
183 if (CRM_Core_Config
::singleton()->moneyvalueformat
!== '%!i') {
184 CRM_Core_Error
::deprecatedFunctionWarning('Having a Money Value format other than !%i is deprecated, please report this on GitLab with the relevant moneyValueFormat you use.');
186 return self
::formatNumericByFormat($amount, CRM_Core_Config
::singleton()->moneyvalueformat
);
190 * Format money for display (just numeric part) according to the current locale with rounding.
192 * At this stage this is conceived as an internal function with the currency wrapper
193 * functions determining the number of places.
195 * This calls the underlying system function but does not handle currency separators.
197 * It's not totally clear when it changes the $amount value but has historical usage.
199 * @param string $amount
200 * @param int $numberOfPlaces
204 protected static function formatLocaleNumericRounded($amount, $numberOfPlaces) {
205 if (!extension_loaded('intl')) {
206 self
::missingIntlNotice();
207 return self
::formatNumericByFormat($amount, '%!.' . $numberOfPlaces . 'i');
209 $money = Money
::of($amount, CRM_Core_Config
::singleton()->defaultCurrency
, new CustomContext($numberOfPlaces), RoundingMode
::CEILING
);
210 $formatter = new \
NumberFormatter(CRM_Core_I18n
::getLocale(), NumberFormatter
::CURRENCY
);
211 $formatter->setSymbol(\NumberFormatter
::CURRENCY_SYMBOL
, '');
212 $formatter->setAttribute(\NumberFormatter
::MIN_FRACTION_DIGITS
, $numberOfPlaces);
213 return $money->formatWith($formatter);
217 * Format money for display (just numeric part) according to the current locale with rounding.
219 * This handles both rounding & replacement of the currency separators for the locale.
221 * @param string $amount
222 * @param string $currency
227 public static function formatLocaleNumericRoundedByCurrency($amount, $currency) {
228 return self
::formatLocaleNumericRoundedByPrecision($amount, self
::getCurrencyPrecision($currency));
232 * Format money for display (just numeric part) according to the current locale with rounding to the supplied precision.
234 * This handles both rounding & replacement of the currency separators for the locale.
236 * @param string $amount
237 * @param int $precision
242 public static function formatLocaleNumericRoundedByPrecision($amount, $precision) {
243 $amount = self
::formatLocaleNumericRounded($amount, $precision);
244 return self
::replaceCurrencySeparators($amount);
248 * Format money for display with rounding to the supplied precision but without padding.
250 * If the string is shorter than the precision trailing zeros are not added to reach the precision
251 * beyond the 2 required for normally currency formatting.
253 * This handles both rounding & replacement of the currency separators for the locale.
255 * @param string $amount
256 * @param int $precision
261 public static function formatLocaleNumericRoundedByOptionalPrecision($amount, $precision) {
262 $decimalPlaces = strlen(substr($amount, strpos($amount, '.') +
1));
263 $amount = self
::formatLocaleNumericRounded($amount, $precision > $decimalPlaces ?
$decimalPlaces : $precision);
264 return self
::replaceCurrencySeparators($amount);
268 * Format money for display (just numeric part) according to the current locale with rounding based on the
269 * default currency for the site.
274 public static function formatLocaleNumericRoundedForDefaultCurrency($amount) {
275 return self
::formatLocaleNumericRoundedByCurrency($amount, self
::getCurrencyPrecision(CRM_Core_Config
::singleton()->defaultCurrency
));
279 * Replace currency separators.
281 * @param string $amount
285 protected static function replaceCurrencySeparators($amount) {
286 $config = CRM_Core_Config
::singleton();
288 ',' => $config->monetaryThousandSeparator
,
289 '.' => $config->monetaryDecimalPoint
,
291 return strtr($amount, $rep);
295 * Format numeric part of currency by the passed in format.
297 * This is envisaged as an internal function, with wrapper functions defining valueFormat
298 * into easily understood functions / variables and handling separator conversions and
301 * @param string $amount
302 * @param string $valueFormat
306 protected static function formatNumericByFormat($amount, $valueFormat) {
307 // money_format() exists only in certain PHP install (CRM-650)
308 // setlocale() affects native gettext (CRM-11054, CRM-9976)
309 if (is_numeric($amount) && function_exists('money_format')) {
310 $lc = setlocale(LC_MONETARY
, 0);
311 setlocale(LC_MONETARY
, 'en_US.utf8', 'en_US', 'en_US.utf8', 'en_US', 'C');
312 $amount = money_format($valueFormat, $amount);
313 setlocale(LC_MONETARY
, $lc);
319 * Emits a notice indicating we have fallen back to a less accurate way of formatting money due to missing intl extension
321 public static function missingIntlNotice() {
322 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'));