public function Fraction::add in Fraction 2.x
Same name and namespace in other branches
- 8 src/Fraction.php \Drupal\fraction\Fraction::add()
Adds another fraction to this one.
Parameters
Fraction $fraction: Another fraction object to add to this one.
Return value
Fraction Returns this Fraction object.
Overrides FractionInterface::add
File
- src/
Fraction.php, line 258
Class
- Fraction
- A simple class for representing and acting upon a fraction.
Namespace
Drupal\fractionCode
public function add(Fraction $fraction) {
// Get the numerator and denominator of each fraction.
$numerator1 = $this
->getNumerator();
$denominator1 = $this
->getDenominator();
$numerator2 = $fraction
->getNumerator();
$denominator2 = $fraction
->getDenominator();
// Calculate the sum of the two fractions.
// Use BCMath if available.
if (function_exists('bcmul') && function_exists('bcadd')) {
$denominator = bcmul($denominator1, $denominator2, 0);
$numerator = bcadd(bcmul($numerator1, $denominator2, 0), bcmul($numerator2, $denominator1, 0), 0);
}
else {
$denominator = $denominator1 * $denominator2;
$numerator = $numerator1 * $denominator2 + $numerator2 * $denominator1;
}
// Save the numerator and denominator.
$this
->setNumerator($numerator);
$this
->setDenominator($denominator);
// Reduce.
$this
->reduce();
return $this;
}