dev/core#2505 Fix formatLocaleNumeric
authoreileen <emcnaughton@wikimedia.org>
Wed, 14 Apr 2021 04:19:58 +0000 (16:19 +1200)
committereileen <emcnaughton@wikimedia.org>
Wed, 14 Apr 2021 05:38:20 +0000 (17:38 +1200)
With the back & forth over formatting this function lost it's original intent and became unused.

I think this gives back the original intent - ie provide a formatted number
with no currency symbol that reflects the locale.

I think this would be usable for https://lab.civicrm.org/dev/core/-/issues/2505
since formatting numbers should be more or less the same as formatting currencies
when only the number is being formatted.

CRM/Utils/Money.php

index e81330950b2affdf1bcb2e3026535da4749284b6..a67ac1b63361b83ceaf5de7da816372d379e3bf1 100644 (file)
@@ -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.
-   *
-   * It's not totally clear when it changes the $amount value but has historical usage.
+   * Note this should not be used in conjunction with any calls to
+   * replaceCurrencySeparators as this function already does that.
    *
-   * @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);
   }
 
   /**