From 38f76de228deb1e5e0ac90069a9e53846cbed357 Mon Sep 17 00:00:00 2001 From: Amast Date: Thu, 12 Dec 2019 14:12:09 +0800 Subject: [PATCH] Add __toString and toDecimalPlaces method. --- src/Utils/Decimal.php | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/Utils/Decimal.php b/src/Utils/Decimal.php index 4800f09..91fd371 100644 --- a/src/Utils/Decimal.php +++ b/src/Utils/Decimal.php @@ -15,17 +15,19 @@ use Illuminate\Support\Arr; class Decimal { protected $source; - protected $dp = 20; + protected $dp; const ROUND_UP = 0; const ROUND_DOWN = 1; - function __construct($v) + function __construct($v, int $dp = 8) { if (!$this->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); + $this->dp = $dp; + $val = $v instanceof Decimal ? $v->getSource() : $v; + $this->source = bcadd($val, "0", $dp); } private function isNumeric($v) @@ -51,11 +53,21 @@ class Decimal throw new \Exception("method $name not found."); } + function __toString(): string + { + return $this->source; + } + function equals($v): bool { return (new Decimal($v))->getSource() == $this->source; } + function toDecimalPlaces(int $dp) + { + return new Decimal($this->source, $dp); + } + function toFixed(int $dp, int $rm = self::ROUND_UP): string { if ($rm == self::ROUND_UP) {