Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

   1  <?php
   2  
   3  namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat;
   4  
   5  use PhpOffice\PhpSpreadsheet\Calculation\MathTrig;
   6  
   7  class FractionFormatter extends BaseFormatter
   8  {
   9      /**
  10       * @param mixed $value
  11       */
  12      public static function format($value, string $format): string
  13      {
  14          $format = self::stripQuotes($format);
  15          $value = (float) $value;
  16          $absValue = abs($value);
  17  
  18          $sign = ($value < 0.0) ? '-' : '';
  19  
  20          $integerPart = floor($absValue);
  21  
  22          $decimalPart = self::getDecimal((string) $absValue);
  23          if ($decimalPart === '0') {
  24              return "{$sign}{$integerPart}";
  25          }
  26          $decimalLength = strlen($decimalPart);
  27          $decimalDivisor = 10 ** $decimalLength;
  28  
  29          /** @var float */
  30          $GCD = MathTrig\Gcd::evaluate($decimalPart, $decimalDivisor);
  31          /** @var float */
  32          $decimalPartx = $decimalPart;
  33  
  34          $adjustedDecimalPart = $decimalPartx / $GCD;
  35          $adjustedDecimalDivisor = $decimalDivisor / $GCD;
  36  
  37          if ((strpos($format, '0') !== false)) {
  38              return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}";
  39          } elseif ((strpos($format, '#') !== false)) {
  40              if ($integerPart == 0) {
  41                  return "{$sign}{$adjustedDecimalPart}/{$adjustedDecimalDivisor}";
  42              }
  43  
  44              return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}";
  45          } elseif ((substr($format, 0, 3) == '? ?')) {
  46              if ($integerPart == 0) {
  47                  $integerPart = '';
  48              }
  49  
  50              return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}";
  51          }
  52  
  53          $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor;
  54  
  55          return "{$sign}{$adjustedDecimalPart}/{$adjustedDecimalDivisor}";
  56      }
  57  
  58      private static function getDecimal(string $value): string
  59      {
  60          $decimalPart = '0';
  61          if (preg_match('/^\\d*[.](\\d*[1-9])0*$/', $value, $matches) === 1) {
  62              $decimalPart = $matches[1];
  63          }
  64  
  65          return $decimalPart;
  66      }
  67  }