Compare commits

..

No commits in common. "main" and "v0.6.0" have entirely different histories.
main ... v0.6.0

View File

@ -15,22 +15,17 @@ use Illuminate\Support\Arr;
class Decimal class Decimal
{ {
protected $source; protected $source;
protected $dp; protected $dp = 20;
// Rounds away from zero.
const ROUND_UP = 0; const ROUND_UP = 0;
// Rounds towards zero.
const ROUND_DOWN = 1; const ROUND_DOWN = 1;
function __construct($v, int $dp = 8) function __construct($v)
{ {
if (!$this->isNumeric($v)) { if (!$this->isNumeric($v)) {
throw new \Exception("value type must be int|float|string|Decimal."); throw new \Exception("value type must be int|float|string|Decimal.");
} }
$this->dp = $dp; $this->source = ($v instanceof Decimal) ? $v->getSource() : bcadd($v, 0, $this->dp);
$val = $v instanceof Decimal ? $v->getSource() : $v;
$this->source = bcadd($val, "0", $dp);
} }
private function isNumeric($v) private function isNumeric($v)
@ -47,7 +42,7 @@ class Decimal
function __call($name, $arguments) function __call($name, $arguments)
{ {
$methods = ['add', 'sub', 'mul', 'div']; $methods = ['add', 'sub', 'mul', 'div'];
if (in_array($name, $methods)) { if (Arr::has($methods, $name)) {
$method = "bc$name"; $method = "bc$name";
$v = new Decimal($arguments[0]); $v = new Decimal($arguments[0]);
return new Decimal($method($this->source, $v->getSource())); return new Decimal($method($this->source, $v->getSource()));
@ -56,19 +51,9 @@ class Decimal
throw new \Exception("method $name not found."); throw new \Exception("method $name not found.");
} }
function __toString(): string
{
return $this->source;
}
function equals($v): bool function equals($v): bool
{ {
return (new Decimal($v))->getSource() == new Decimal($this->source); return (new Decimal($v))->getSource() == $this->source;
}
function toDecimalPlaces(int $dp, int $rm = self::ROUND_UP): Decimal
{
return new Decimal($this->toFixed($dp, $rm), $dp);
} }
function toFixed(int $dp, int $rm = self::ROUND_UP): string function toFixed(int $dp, int $rm = self::ROUND_UP): string