Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.
   1  <?php
   2  
   3  namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard;
   4  
   5  use NumberFormatter;
   6  use PhpOffice\PhpSpreadsheet\Exception;
   7  
   8  class Percentage extends NumberBase implements Wizard
   9  {
  10      /**
  11       * @param int $decimals number of decimal places to display, in the range 0-30
  12       * @param ?string $locale Set the locale for the percentage format; or leave as the default null.
  13       *          If provided, Locale values must be a valid formatted locale string (e.g. 'en-GB', 'fr', uz-Arab-AF).
  14       *
  15       * @throws Exception If a provided locale code is not a valid format
  16       */
  17      public function __construct(int $decimals = 2, ?string $locale = null)
  18      {
  19          $this->setDecimals($decimals);
  20          $this->setLocale($locale);
  21      }
  22  
  23      protected function getLocaleFormat(): string
  24      {
  25          $formatter = new Locale($this->fullLocale, NumberFormatter::PERCENT);
  26  
  27          return $this->decimals > 0
  28              ? str_replace('0', '0.' . str_repeat('0', $this->decimals), $formatter->format())
  29              : $formatter->format();
  30      }
  31  
  32      public function format(): string
  33      {
  34          if ($this->localeFormat !== null) {
  35              return $this->localeFormat;
  36          }
  37  
  38          return sprintf('0%s%%', $this->decimals > 0 ? '.' . str_repeat('0', $this->decimals) : null);
  39      }
  40  }