Add __toString and toDecimalPlaces method.

This commit is contained in:
Amast 2019-12-12 14:12:09 +08:00
parent 8469f4124c
commit 38f76de228

View File

@ -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) {