Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. BigDecimal.php

function BigDecimal::sqrt

Returns the square root of this number, rounded down to the given number of decimals.

Throws

\InvalidArgumentException If the scale is negative.

NegativeNumberException If this number is negative.

File

vendor/brick/math/src/BigDecimal.php, line 414

Class

BigDecimal
Immutable, arbitrary-precision signed decimal numbers.

Namespace

Brick\Math

Code

public function sqrt(int $scale) : BigDecimal {
    if ($scale < 0) {
        throw new \InvalidArgumentException('Scale cannot be negative.');
    }
    if ($this->value === '0') {
        return new BigDecimal('0', $scale);
    }
    if ($this->value[0] === '-') {
        throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
    }
    $value = $this->value;
    $addDigits = 2 * $scale - $this->scale;
    if ($addDigits > 0) {
        // add zeros
        $value .= \str_repeat('0', $addDigits);
    }
    elseif ($addDigits < 0) {
        // trim digits
        if (-$addDigits >= \strlen($this->value)) {
            // requesting a scale too low, will always yield a zero result
            return new BigDecimal('0', $scale);
        }
        $value = \substr($value, 0, $addDigits);
    }
    $value = Calculator::get()->sqrt($value);
    return new BigDecimal($value, $scale);
}

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal