diff --git a/src/Utils/Decimal.php b/src/Utils/Decimal.php new file mode 100644 index 0000000..4800f09 --- /dev/null +++ b/src/Utils/Decimal.php @@ -0,0 +1,81 @@ +isNumeric($v)) { + throw new \Exception("value type must be int|float|string|Decimal."); + } + + $this->source = ($v instanceof Decimal) ? $v->getSource() : bcadd($v, 0, $this->dp); + } + + private function isNumeric($v) + { + if ($v instanceof Decimal) return true; + return is_numeric($v); + } + + function getSource() + { + return $this->source; + } + + function __call($name, $arguments) + { + $methods = ['add', 'sub', 'mul', 'div']; + if (Arr::has($methods, $name)) { + $method = "bc$name"; + $v = new Decimal($arguments[0]); + return new Decimal($method($this->source, $v->getSource())); + } + + throw new \Exception("method $name not found."); + } + + function equals($v): bool + { + return (new Decimal($v))->getSource() == $this->source; + } + + function toFixed(int $dp, int $rm = self::ROUND_UP): string + { + if ($rm == self::ROUND_UP) { + return number_format($this->source, $dp, ".", ""); + } + + if ($rm == self::ROUND_DOWN) { + return bcadd($this->source, 0, $dp); + } + + throw new \Exception("$rm must be " . self::ROUND_UP . ' or ' . self::ROUND_DOWN); + } + + function toInt(): int + { + return (int) $this->source; + } + + function toFloat(): float + { + return (float) $this->source; + } +}