Litipk\BigNumbers\Decimal::fromString PHP Méthode

fromString() public static méthode

public static fromString ( string $strValue, integer $scale = null, boolean $removeZeros = false ) : Decimal
$strValue string
$scale integer
$removeZeros boolean If true then removes trailing zeros from the number representation
Résultat Decimal
    public static function fromString($strValue, $scale = null, $removeZeros = false)
    {
        self::paramsValidation($strValue, $scale);
        if (!is_string($strValue)) {
            throw new InvalidArgumentTypeException(['string'], is_object($strValue) ? get_class($strValue) : gettype($strValue), '$strVlue must be of type string.');
        } elseif (preg_match('/^([+\\-]?)0*(([1-9][0-9]*|[0-9])(\\.[0-9]+)?)$/', $strValue, $captures) === 1) {
            // Now it's time to strip leading zeros in order to normalize inner values
            $value = self::normalizeSign($captures[1]) . $captures[2];
            $min_scale = isset($captures[4]) ? max(0, strlen($captures[4]) - 1) : 0;
        } elseif (preg_match('/([+\\-]?)0*([0-9](\\.[0-9]+)?)[eE]([+\\-]?)(\\d+)/', $strValue, $captures) === 1) {
            $mantissa_scale = max(strlen($captures[3]) - 1, 0);
            $exp_val = (int) $captures[5];
            if (self::normalizeSign($captures[4]) === '') {
                $min_scale = max($mantissa_scale - $exp_val, 0);
                $tmp_multiplier = bcpow(10, $exp_val);
            } else {
                $min_scale = $mantissa_scale + $exp_val;
                $tmp_multiplier = bcpow(10, -$exp_val, $exp_val);
            }
            $value = self::normalizeSign($captures[1]) . bcmul($captures[2], $tmp_multiplier, max($min_scale, $scale !== null ? $scale : 0));
        } else {
            if (preg_match('/([+\\-]?)(inf|Inf|INF)/', $strValue, $captures) === 1) {
                if ($captures[1] === '-') {
                    return InfiniteDecimal::getNegativeInfinite();
                } else {
                    return InfiniteDecimal::getPositiveInfinite();
                }
            } else {
                throw new \InvalidArgumentException('$strValue must be a string that represents uniquely a float point number.');
            }
        }
        $scale = $scale !== null ? $scale : $min_scale;
        if ($scale < $min_scale) {
            $value = self::innerRound($value, $scale);
        }
        if ($removeZeros) {
            $value = self::removeTrailingZeros($value, $scale);
        }
        return new static($value, $scale);
    }

Usage Example

 public function testPositiveNegativeDecimalAdd()
 {
     $n1 = Decimal::fromString('3.45');
     $n2 = Decimal::fromString('-7.67');
     $this->assertTrue($n1->add($n2)->equals(Decimal::fromString('-4.22')));
     $this->assertTrue($n2->add($n1)->equals(Decimal::fromString('-4.22')));
 }
All Usage Examples Of Litipk\BigNumbers\Decimal::fromString