You are here

public function Fraction::toDecimal in Fraction 2.x

Same name and namespace in other branches
  1. 8 src/Fraction.php \Drupal\fraction\Fraction::toDecimal()

Calculates the decimal equivalent of the fraction.

Parameters

int $precision: The desired decimal precision, defaults to 0.

bool $auto_precision: Boolean, whether or not the precision should be automatically calculated. This option provides more precision when you need it, and less when you don't. If set to TRUE, it will try to determine the maximum precision (this only works if the denominator is base 10). If the resulting precision is greater than $precision, it will be used instead.

Return value

string Returns the decimal equivalent of the fraction as a PHP string.

Overrides FractionInterface::toDecimal

File

src/Fraction.php, line 131

Class

Fraction
A simple class for representing and acting upon a fraction.

Namespace

Drupal\fraction

Code

public function toDecimal(int $precision = 0, bool $auto_precision = FALSE) {

  // Get the numerator and denominator.
  $numerator = $this
    ->getNumerator();
  $denominator = $this
    ->getDenominator();

  // If auto precision is on figure out the maximum precision.
  if ($auto_precision) {

    // If the denominator is base-10, max precision is the number of zeroes
    // in the denominator.
    if ($denominator % 10 == 0) {
      $max_precision = strlen($denominator) - 1;
    }
    elseif ($denominator == 1) {
      $max_precision = 0;
    }
    else {
      $max_precision = strlen($denominator);
    }

    // Use the greater of the two precisions.
    $precision = $max_precision > $precision ? $max_precision : $precision;
  }

  // Divide the numerator by the denominator (using BCMath if available).
  if (function_exists('bcdiv')) {

    // Divide the numerator and denominator, with extra precision.
    $value = bcdiv($numerator, $denominator, $precision + 1);

    // Return a decimal string rounded to the final precision.
    return $this
      ->bcRound($value, $precision);
  }
  else {
    return (string) round($numerator / $denominator, $precision);
  }
}