Merge pull request #22704 from braders/remove-invalidprofiles-template-variable
[civicrm-core.git] / CRM / Utils / Money.php
index e81330950b2affdf1bcb2e3026535da4749284b6..3cc33e4226cc7757f95b975aa93afeb7e2109033 100644 (file)
@@ -146,9 +146,9 @@ class CRM_Utils_Money {
    * 1.234 != 1.236 with a currency precision of 2 decimal points
    * 1.300 != 1.200 with a currency precision of 2 decimal points
    *
-   * @param $value1
-   * @param $value2
-   * @param $currency
+   * @param int|float $value1
+   * @param int|float $value2
+   * @param string $currency
    *
    * @return bool
    */
@@ -159,18 +159,24 @@ class CRM_Utils_Money {
   }
 
   /**
-   * Format money for display (just numeric part) according to the current locale.
+   * Format money (or number) for display (just numeric part) according to the current or supplied locale.
    *
-   * This calls the underlying system function but does not handle currency separators.
+   * Note this should not be used in conjunction with any calls to
+   * replaceCurrencySeparators as this function already does that.
    *
-   * It's not totally clear when it changes the $amount value but has historical usage.
-   *
-   * @param $amount
+   * @param string $amount
+   * @param string $locale
+   * @param string $currency
+   * @param int $numberOfPlaces
    *
    * @return string
+   * @throws \Brick\Money\Exception\UnknownCurrencyException
    */
-  protected static function formatLocaleNumeric($amount) {
-    return self::formatNumericByFormat($amount);
+  protected static function formatLocaleNumeric(string $amount, $locale = NULL, $currency = NULL, $numberOfPlaces = 2): string {
+    $money = Money::of($amount, $currency ?? CRM_Core_Config::singleton()->defaultCurrency, new CustomContext($numberOfPlaces), RoundingMode::HALF_UP);
+    $formatter = new \NumberFormatter($locale ?? CRM_Core_I18n::getLocale(), NumberFormatter::DECIMAL);
+    $formatter->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $numberOfPlaces);
+    return $money->formatWith($formatter);
   }
 
   /**
@@ -188,7 +194,7 @@ class CRM_Utils_Money {
    *
    * @return string
    */
-  protected static function formatUSLocaleNumericRounded($amount, int $numberOfPlaces): string {
+  public static function formatUSLocaleNumericRounded($amount, int $numberOfPlaces): string {
     if (!extension_loaded('intl') || !is_numeric($amount)) {
       // @todo - we should not attempt to format non-numeric strings. For now
       // these will not fail but will give notices on php 7.4