This commit is contained in:
Amast 2019-12-12 14:40:51 +08:00
parent 83445da8b2
commit 59f6635936

View File

@ -16,7 +16,10 @@ class Decimal
{ {
protected $source; protected $source;
protected $dp; protected $dp;
// 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, int $dp = 8)
@ -44,7 +47,7 @@ class Decimal
function __call($name, $arguments) function __call($name, $arguments)
{ {
$methods = ['add', 'sub', 'mul', 'div']; $methods = ['add', 'sub', 'mul', 'div'];
if (Arr::has($methods, $name)) { if (in_array($name, $methods)) {
$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()));
@ -63,9 +66,9 @@ class Decimal
return (new Decimal($v))->getSource() == new Decimal($this->source); return (new Decimal($v))->getSource() == new Decimal($this->source);
} }
function toDecimalPlaces(int $dp) function toDecimalPlaces(int $dp, int $rm = self::ROUND_UP): Decimal
{ {
return new Decimal($this->source, $dp); 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