From 8469f4124c26c2aa3912d0041b552506d8a8384e Mon Sep 17 00:00:00 2001 From: Amast Date: Thu, 12 Dec 2019 12:58:24 +0800 Subject: [PATCH] Add decimal util. --- src/Utils/Decimal.php | 81 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/Utils/Decimal.php 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; + } +}