Example #1
0
 /**
  * Calculates the greatest common divisor of the ratio's dividend and divisor.
  *
  * @return Decimal
  */
 public function greatestCommonDivisor() : Decimal
 {
     if (null !== $this->gcd) {
         return $this->gcd;
     }
     $cleared = $this->clearDecimals();
     $a = $cleared->dividend->toString();
     $b = $cleared->divisor->toString();
     while (bccomp($b, '0') !== 0) {
         list($a, $b) = [$b, bcmod($a, $b)];
     }
     $gcd = new Decimal($a);
     return $this->gcd = $gcd->abs();
 }
Example #2
0
 public function testAbs()
 {
     $decimal1 = new Decimal("-123.123");
     $this->assertEquals("123.123", (string) $decimal1->abs());
 }
Example #3
0
 /**
  * Divides this decimal by another.
  *
  * @param Decimal $other
  * @param int     $scale
  *
  * @return Decimal
  */
 public function divideBy(Decimal $other, int $scale = null) : Decimal
 {
     if ($other->isZero()) {
         throw new \LogicException('Cannot divide by zero.');
     }
     if ($other->isOne()) {
         return $this;
     }
     if (null === $scale) {
         // Determine a reasonable scale to avoid too much loss of precision.
         $abs = $this->abs();
         $otherAbs = $other->abs();
         $otherLog10 = self::computeLog10($otherAbs->value, $otherAbs->numberOfDecimalPlaces(), 1);
         $log10 = self::computeLog10($abs->value, $abs->numberOfDecimalPlaces(), 1) - $otherLog10;
         $totalDecimalPlaces = $this->numberOfDecimalPlaces() + $other->numberOfDecimalPlaces();
         $maxSignificantDigits = max($this->numberOfSignificantDigits(), $other->numberOfSignificantDigits());
         $scale = (int) max($totalDecimalPlaces, $maxSignificantDigits - max(ceil($log10), 0), ceil(-$log10) + 1);
     }
     $result = bcdiv($this->value, $other->value, $scale);
     return static::fromString($result);
 }