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
::deprecatedWarning('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 $currency = $config->defaultCurrency
;
78 $amount = self
::formatLocaleNumericRoundedByCurrency($amount, $currency);
82 if (!self
::$_currencySymbols) {
83 self
::$_currencySymbols = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'currency', [
84 'keyColumn' => 'name',
85 'labelColumn' => 'symbol',
89 // ensure $currency is a valid currency code
90 // for backwards-compatibility, also accept one space instead of a currency
91 if ($currency != ' ' && !array_key_exists($currency, self
::$_currencySymbols)) {
92 throw new CRM_Core_Exception("Invalid currency \"{$currency}\"");
95 if ($currency === ' ') {
96 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');
99 $amount = self
::formatNumericByFormat($amount, $valueFormat);
100 // If it contains tags, means that HTML was passed and the
101 // amount is already converted properly,
102 // so don't mess with it again.
103 // @todo deprecate handling for the html tags because .... WTF
104 if (strpos($amount, '<') === FALSE) {
105 $amount = self
::replaceCurrencySeparators($amount);
111 '%c' => CRM_Utils_Array
::value($currency, self
::$_currencySymbols, $currency),
113 return strtr($format, $replacements);
117 * This is a placeholder function for calculating the number of decimal places for a currency.
119 * Currently code assumes 2 decimal places but some currencies (bitcoin, middle eastern) have
120 * more. By using this function we can signpost the locations where the number of decimal places is
121 * currency specific for future enhancement.
123 * @param string $currency
126 * Number of decimal places.
128 public static function getCurrencyPrecision($currency = NULL) {
133 * Subtract currencies using integers instead of floats, to preserve precision
135 * @param string|float $leftOp
136 * @param string|float $rightOp
137 * @param string $currency
140 * Result of subtracting $rightOp from $leftOp to the precision of $currency
142 public static function subtractCurrencies($leftOp, $rightOp, $currency) {
143 if (is_numeric($leftOp) && is_numeric($rightOp)) {
144 $leftMoney = Money
::of($leftOp, $currency, new DefaultContext(), RoundingMode
::CEILING
);
145 $rightMoney = Money
::of($rightOp, $currency, new DefaultContext(), RoundingMode
::CEILING
);
146 return $leftMoney->minus($rightMoney)->getAmount()->toFloat();
151 * Tests if two currency values are equal, taking into account the currency's
152 * precision, so that the two values are compared as integers after rounding.
156 * 1.231 == 1.232 with a currency precision of 2 decimal points
157 * 1.234 != 1.236 with a currency precision of 2 decimal points
158 * 1.300 != 1.200 with a currency precision of 2 decimal points
166 public static function equals($value1, $value2, $currency) {
167 $precision = pow(10, self
::getCurrencyPrecision($currency));
169 return (int) round($value1 * $precision) == (int) round($value2 * $precision);
173 * Format money for display (just numeric part) according to the current locale.
175 * This calls the underlying system function but does not handle currency separators.
177 * It's not totally clear when it changes the $amount value but has historical usage.
183 protected static function formatLocaleNumeric($amount) {
184 if (CRM_Core_Config
::singleton()->moneyvalueformat
!== '%!i') {
185 CRM_Core_Error
::deprecatedWarning('Having a Money Value format other than !%i is deprecated, please report this on GitLab with the relevant moneyValueFormat you use.');
187 return self
::formatNumericByFormat($amount, CRM_Core_Config
::singleton()->moneyvalueformat
);
191 * Format money for display (just numeric part) according to the current locale with rounding.
193 * At this stage this is conceived as an internal function with the currency wrapper
194 * functions determining the number of places.
196 * This calls the underlying system function but does not handle currency separators.
198 * It's not totally clear when it changes the $amount value but has historical usage.
200 * @param string $amount
201 * @param int $numberOfPlaces
205 protected static function formatLocaleNumericRounded($amount, $numberOfPlaces) {
206 if (!extension_loaded('intl')) {
207 self
::missingIntlNotice();
208 return self
::formatNumericByFormat($amount, '%!.' . $numberOfPlaces . 'i');
210 $money = Money
::of($amount, CRM_Core_Config
::singleton()->defaultCurrency
, new CustomContext($numberOfPlaces), RoundingMode
::CEILING
);
211 $formatter = new \
NumberFormatter(CRM_Core_I18n
::getLocale(), NumberFormatter
::CURRENCY
);
212 $formatter->setSymbol(\NumberFormatter
::CURRENCY_SYMBOL
, '');
213 $formatter->setAttribute(\NumberFormatter
::MIN_FRACTION_DIGITS
, $numberOfPlaces);
214 return $money->formatWith($formatter);
218 * Format money for display (just numeric part) according to the current locale with rounding.
220 * This handles both rounding & replacement of the currency separators for the locale.
222 * @param string $amount
223 * @param string $currency
228 public static function formatLocaleNumericRoundedByCurrency($amount, $currency) {
229 return self
::formatLocaleNumericRoundedByPrecision($amount, self
::getCurrencyPrecision($currency));
233 * Format money for display (just numeric part) according to the current locale with rounding to the supplied precision.
235 * This handles both rounding & replacement of the currency separators for the locale.
237 * @param string $amount
238 * @param int $precision
243 public static function formatLocaleNumericRoundedByPrecision($amount, $precision) {
244 $amount = self
::formatLocaleNumericRounded($amount, $precision);
245 return self
::replaceCurrencySeparators($amount);
249 * Format money for display with rounding to the supplied precision but without padding.
251 * If the string is shorter than the precision trailing zeros are not added to reach the precision
252 * beyond the 2 required for normally currency formatting.
254 * This handles both rounding & replacement of the currency separators for the locale.
256 * @param string $amount
257 * @param int $precision
262 public static function formatLocaleNumericRoundedByOptionalPrecision($amount, $precision) {
263 $decimalPlaces = strlen(substr($amount, strpos($amount, '.') +
1));
264 $amount = self
::formatLocaleNumericRounded($amount, $precision > $decimalPlaces ?
$decimalPlaces : $precision);
265 return self
::replaceCurrencySeparators($amount);
269 * Format money for display (just numeric part) according to the current locale with rounding based on the
270 * default currency for the site.
275 public static function formatLocaleNumericRoundedForDefaultCurrency($amount) {
276 return self
::formatLocaleNumericRoundedByCurrency($amount, self
::getCurrencyPrecision(CRM_Core_Config
::singleton()->defaultCurrency
));
280 * Replace currency separators.
282 * @param string $amount
286 protected static function replaceCurrencySeparators($amount) {
287 $config = CRM_Core_Config
::singleton();
289 ',' => $config->monetaryThousandSeparator
,
290 '.' => $config->monetaryDecimalPoint
,
292 return strtr($amount, $rep);
296 * Format numeric part of currency by the passed in format.
298 * This is envisaged as an internal function, with wrapper functions defining valueFormat
299 * into easily understood functions / variables and handling separator conversions and
302 * @param string $amount
303 * @param string $valueFormat
307 protected static function formatNumericByFormat($amount, $valueFormat) {
308 // money_format() exists only in certain PHP install (CRM-650)
309 // setlocale() affects native gettext (CRM-11054, CRM-9976)
310 if (is_numeric($amount) && function_exists('money_format')) {
311 $lc = setlocale(LC_MONETARY
, 0);
312 setlocale(LC_MONETARY
, 'en_US.utf8', 'en_US', 'en_US.utf8', 'en_US', 'C');
313 $amount = money_format($valueFormat, $amount);
314 setlocale(LC_MONETARY
, $lc);
320 * Emits a notice indicating we have fallen back to a less accurate way of formatting money due to missing intl extension
322 public static function missingIntlNotice() {
323 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'));