Add decimal util.
This commit is contained in:
parent
065808e0fb
commit
8469f4124c
81
src/Utils/Decimal.php
Normal file
81
src/Utils/Decimal.php
Normal file
|
@ -0,0 +1,81 @@
|
|||
<?php
|
||||
|
||||
namespace PdToolKit\Utils;
|
||||
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
/**
|
||||
* Class Decimal
|
||||
* @package PdToolKit\Utils
|
||||
* @method Decimal add(int|float|string|Decimal $v);
|
||||
* @method Decimal sub(int|float|string|Decimal $v);
|
||||
* @method Decimal mul(int|float|string|Decimal $v);
|
||||
* @method Decimal div(int|float|string|Decimal $v);
|
||||
*/
|
||||
class Decimal
|
||||
{
|
||||
protected $source;
|
||||
protected $dp = 20;
|
||||
const ROUND_UP = 0;
|
||||
const ROUND_DOWN = 1;
|
||||
|
||||
function __construct($v)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user