Litipk\BigNumbers\Decimal::fromFloat PHP Method

fromFloat() public static method

public static fromFloat ( float $fltValue, integer $scale = null, boolean $removeZeros = false ) : Decimal
$fltValue float
$scale integer
$removeZeros boolean If true then removes trailing zeros from the number representation
return Decimal
    public static function fromFloat($fltValue, $scale = null, $removeZeros = false)
    {
        self::paramsValidation($fltValue, $scale);
        if (!is_float($fltValue)) {
            throw new InvalidArgumentTypeException(['float'], is_object($fltValue) ? get_class($fltValue) : gettype($fltValue), '$fltValue must be of type float');
        } elseif ($fltValue === INF) {
            return InfiniteDecimal::getPositiveInfinite();
        } elseif ($fltValue === -INF) {
            return InfiniteDecimal::getNegativeInfinite();
        } elseif (is_nan($fltValue)) {
            throw new \DomainException("To ensure consistency, this class doesn't handle NaN objects.");
        }
        $defaultScale = 16;
        $strValue = (string) $fltValue;
        if (preg_match("/^ (?P<int> \\d*) (?: \\. (?P<dec> \\d+) ) E (?P<sign>[\\+\\-]) (?P<exp>\\d+) \$/x", $strValue, $capture)) {
            if ($scale === null) {
                if ($capture['sign'] == '-') {
                    $scale = $capture['exp'] + strlen($capture['dec']);
                } else {
                    $scale = $defaultScale;
                }
            }
            $strValue = number_format($fltValue, $scale, '.', '');
        }
        if ($scale === null) {
            $scale = $defaultScale;
        }
        if ($removeZeros) {
            $strValue = self::removeTrailingZeros($strValue, $scale);
        }
        return new static($strValue, $scale);
    }

Usage Example

コード例 #1
0
 public function testNegativeNumbers()
 {
     $this->assertFalse(Decimal::fromInteger(-1)->isZero());
     $this->assertFalse(Decimal::fromFloat(-1.0)->isZero());
     $this->assertFalse(Decimal::fromFloat(-0.1)->isZero());
     $this->assertFalse(Decimal::fromString('-1')->isZero());
 }
All Usage Examples Of Litipk\BigNumbers\Decimal::fromFloat