php金额计算

<?php


namespace core\utils;


/**
 * 用于金额计算
 * Class Decimal
 * @package extend\utils
 */
class Decimal
{
    private $value;

    /**
     * @param string $value
     * @return Decimal
     */
    static function newDecimal($value = '0')
    {
        return new Decimal($value);
    }

    public function __construct($value = '0')
    {
        $this->value = $this->normalize($value);
    }

    private function normalize($value)
    {
        return strval(str_replace(',', '', $value));
    }

    public function __toString()
    {
        return $this->value;
    }

    /**
     * 加法
     * @param string|Decimal $operand  数字/字符串或者Decimal对象
     * @param int $scale 小数点
     * @return $this
     */
    public function add($operand, $scale = 2)
    {
        $this->value = bcadd($this->value, $operand, $scale);
        return $this;
    }

    /**
     * 减法
      * @param string|Decimal $operand  数字/字符串或者Decimal对象
     * @param int $scale 小数点
     * @return $this
     */
    public function subtract($operand, $scale = 2)
    {
        $this->value = bcsub($this->value, $operand, $scale);
        return $this;
    }

    /**
     * 乘法
      * @param string|Decimal $operand  数字/字符串或者Decimal对象
     * @param int $scale 小数点
     * @return $this
     */
    public function multiply($operand, $scale = 2)
    {
        $this->value = bcmul($this->value, $operand, $scale);
        return $this;
    }

    /**
     * 除法
      * @param string|Decimal $operand  数字/字符串或者Decimal对象
     * @param int $scale 小数点
     * @return $this
     */
    public function divide($operand, $scale = 2)
    {
        $this->value = bcdiv($this->value, $operand, $scale);
        return $this;
    }

    /**
     * 获取计算后的数据
     */
    public function getValue()
    {
        return $this->value;
    }
}
posted @ 2024-07-11 14:00  Anbin啊  阅读(27)  评论(0)    收藏  举报