You are here

public function Fraction::reduce in Fraction 2.x

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

Reduces the fraction to its simplest form.

Return value

Fraction Returns this Fraction object.

Overrides FractionInterface::reduce

4 calls to Fraction::reduce()
Fraction::add in src/Fraction.php
Adds another fraction to this one.
Fraction::divide in src/Fraction.php
Divides this fraction by another one.
Fraction::multiply in src/Fraction.php
Multiplies this fraction with another one.
Fraction::subtract in src/Fraction.php
Subtracts another fraction from this one.

File

src/Fraction.php, line 212

Class

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

Namespace

Drupal\fraction

Code

public function reduce() {

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

  // Calculate the greatest common divisor.
  $gcd = $this
    ->gcd();

  // Divide the numerator and denominator by the gcd.
  // Use BCMath division if available.
  if (function_exists('bcdiv')) {
    $numerator = bcdiv($numerator, $gcd, 0);
    $denominator = bcdiv($denominator, $gcd, 0);
  }
  else {
    $numerator = $numerator / $gcd;
    $denominator = $denominator / $gcd;
  }

  // Save the numerator and denominator.
  $this
    ->setNumerator($numerator);
  $this
    ->setDenominator($denominator);
  return $this;
}