public function Fraction::subtract in Fraction 8
Same name and namespace in other branches
- 2.x src/Fraction.php \Drupal\fraction\Fraction::subtract()
Subtracts another fraction from this one.
Parameters
Fraction $fraction: Another fraction object to subtract this one.
Return value
Fraction Returns this Fraction object.
Overrides FractionInterface::subtract
File
- src/
Fraction.php, line 298
Class
- Fraction
- A simple class for representing and acting upon a fraction.
Namespace
Drupal\fractionCode
public function subtract(Fraction $fraction) {
// Get the numerator and denominator of each fraction.
$numerator1 = $this
->getNumerator();
$denominator1 = $this
->getDenominator();
$numerator2 = $fraction
->getNumerator();
$denominator2 = $fraction
->getDenominator();
// Calculate the difference of the two fractions.
// Use BCMath if available.
if (function_exists('bcmul') && function_exists('bcsub')) {
$denominator = bcmul($denominator1, $denominator2, 0);
$numerator = bcsub(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);
return $this;
}