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\Math\RoundingMode
;
25 class CRM_Utils_Money
{
26 public static $_currencySymbols = NULL;
29 * Format a monetary string.
31 * Format a monetary string basing on the amount provided,
32 * ISO currency code provided and a format string consisting of:
34 * %a - the formatted amount
35 * %C - the currency ISO code (e.g., 'USD') if provided
36 * %c - the currency symbol (e.g., '$') if available
38 * @param float $amount
39 * The monetary amount to display (1234.56).
40 * @param string $currency
41 * The three-letter ISO currency code ('USD').
42 * @param string $format
43 * The desired currency format.
44 * @param bool $onlyNumber
45 * @param string $valueFormat
46 * The desired monetary value display format (e.g. '%!i').
49 * formatted monetary string
52 public static function format($amount, $currency = NULL, $format = NULL, $onlyNumber = FALSE, $valueFormat = NULL) {
54 if (CRM_Utils_System
::isNull($amount)) {
58 $config = CRM_Core_Config
::singleton();
61 $format = $config->moneyformat
;
65 $valueFormat = $config->moneyvalueformat
;
68 if (!empty($valueFormat) && $valueFormat !== '%!i') {
69 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.');
73 // money_format() exists only in certain PHP install (CRM-650)
74 if (is_numeric($amount) and function_exists('money_format')) {
75 $amount = money_format($valueFormat, $amount);
80 if (!self
::$_currencySymbols) {
81 self
::$_currencySymbols = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'currency', [
82 'keyColumn' => 'name',
83 'labelColumn' => 'symbol',
88 $currency = $config->defaultCurrency
;
91 // ensure $currency is a valid currency code
92 // for backwards-compatibility, also accept one space instead of a currency
93 if ($currency != ' ' && !array_key_exists($currency, self
::$_currencySymbols)) {
94 throw new CRM_Core_Exception("Invalid currency \"{$currency}\"");
97 $amount = self
::formatNumericByFormat($amount, $valueFormat);
98 // If it contains tags, means that HTML was passed and the
99 // amount is already converted properly,
100 // so don't mess with it again.
101 // @todo deprecate handling for the html tags because .... WTF
102 if (strpos($amount, '<') === FALSE) {
103 $amount = self
::replaceCurrencySeparators($amount);
109 '%c' => CRM_Utils_Array
::value($currency, self
::$_currencySymbols, $currency),
111 return strtr($format, $replacements);
115 * This is a placeholder function for calculating the number of decimal places for a currency.
117 * Currently code assumes 2 decimal places but some currencies (bitcoin, middle eastern) have
118 * more. By using this function we can signpost the locations where the number of decimal places is
119 * currency specific for future enhancement.
121 * @param string $currency
124 * Number of decimal places.
126 public static function getCurrencyPrecision($currency = NULL) {
131 * Subtract currencies using integers instead of floats, to preserve precision
133 * @param string|float $leftOp
134 * @param string|float $rightOp
135 * @param string $currency
138 * Result of subtracting $rightOp from $leftOp to the precision of $currency
140 public static function subtractCurrencies($leftOp, $rightOp, $currency) {
141 if (is_numeric($leftOp) && is_numeric($rightOp)) {
142 $leftMoney = Money
::of($leftOp, $currency, new DefaultContext(), RoundingMode
::CEILING
);
143 $rightMoney = Money
::of($rightOp, $currency, new DefaultContext(), RoundingMode
::CEILING
);
144 return $leftMoney->minus($rightMoney)->getAmount()->toFloat();
149 * Tests if two currency values are equal, taking into account the currency's
150 * precision, so that the two values are compared as integers after rounding.
154 * 1.231 == 1.232 with a currency precision of 2 decimal points
155 * 1.234 != 1.236 with a currency precision of 2 decimal points
156 * 1.300 != 1.200 with a currency precision of 2 decimal points
164 public static function equals($value1, $value2, $currency) {
165 $precision = pow(10, self
::getCurrencyPrecision($currency));
167 return (int) round($value1 * $precision) == (int) round($value2 * $precision);
171 * Format money for display (just numeric part) according to the current locale.
173 * This calls the underlying system function but does not handle currency separators.
175 * It's not totally clear when it changes the $amount value but has historical usage.
181 protected static function formatLocaleNumeric($amount) {
182 if (CRM_Core_Config
::singleton()->moneyvalueformat
!== '%!i') {
183 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.');
185 return self
::formatNumericByFormat($amount, CRM_Core_Config
::singleton()->moneyvalueformat
);
189 * Format money for display (just numeric part) according to the current locale with rounding.
191 * At this stage this is conceived as an internal function with the currency wrapper
192 * functions determining the number of places.
194 * This calls the underlying system function but does not handle currency separators.
196 * It's not totally clear when it changes the $amount value but has historical usage.
198 * @param string $amount
199 * @param int $numberOfPlaces
203 protected static function formatLocaleNumericRounded($amount, $numberOfPlaces) {
204 return self
::formatLocaleNumeric(round($amount, $numberOfPlaces));
208 * Format money for display (just numeric part) according to the current locale with rounding.
210 * This handles both rounding & replacement of the currency separators for the locale.
212 * @param string $amount
213 * @param string $currency
218 public static function formatLocaleNumericRoundedByCurrency($amount, $currency) {
219 $amount = self
::formatLocaleNumericRounded($amount, self
::getCurrencyPrecision($currency));
220 return self
::replaceCurrencySeparators($amount);
224 * Format money for display (just numeric part) according to the current locale with rounding based on the
225 * default currency for the site.
230 public static function formatLocaleNumericRoundedForDefaultCurrency($amount) {
231 return self
::formatLocaleNumericRoundedByCurrency($amount, self
::getCurrencyPrecision(CRM_Core_Config
::singleton()->defaultCurrency
));
235 * Replace currency separators.
237 * @param string $amount
241 protected static function replaceCurrencySeparators($amount) {
242 $config = CRM_Core_Config
::singleton();
244 ',' => $config->monetaryThousandSeparator
,
245 '.' => $config->monetaryDecimalPoint
,
247 return strtr($amount, $rep);
251 * Format numeric part of currency by the passed in format.
253 * This is envisaged as an internal function, with wrapper functions defining valueFormat
254 * into easily understood functions / variables and handling separator conversions and
257 * @param string $amount
258 * @param string $valueFormat
262 protected static function formatNumericByFormat($amount, $valueFormat) {
263 // money_format() exists only in certain PHP install (CRM-650)
264 // setlocale() affects native gettext (CRM-11054, CRM-9976)
265 if (is_numeric($amount) && function_exists('money_format')) {
266 $lc = setlocale(LC_MONETARY
, 0);
267 setlocale(LC_MONETARY
, 'en_US.utf8', 'en_US', 'en_US.utf8', 'en_US', 'C');
268 $amount = money_format($valueFormat, $amount);
269 setlocale(LC_MONETARY
, $lc);