在开发中,我们经常会遇到一些精度计算的问题,至于为何会出现精度问题,在此不再赘述,PHP提供了一些内置函数来解决精度的问题,但是如果计算的数值个数较多,嵌套起来会比较麻烦,并且表达式如果有修改,改起来也很麻烦,使用该类可以解决嵌套和后期修改的麻烦,并且能使代码更加的优雅!
<?php
/**
* 精确计算类,支持链式调用
*/
class AccuracyCal
{
//第一个要计算的数值
public $number = 0;
//精度计算时保留的小数点位数
public $scale = 2;
//计算结果
public $result = 0;
/**
* AccuracyCal constructor.
* @param int $scale 精确计算是保留的小数位数
*/
public function __construct($scale = 2)
{
$this->scale = $scale;
}
/**
* 第一个参与运算的数值,如果调用,需在最前面调用
* @param $number 第一个要计算的数字
* 2020/8/14 15:52
* by 991399725@qq.com
*/
public function number($number)
{
$this->result = $this->number = $number;
return $this;
}
/**
* 精确计算:加
* @param $number
* @return $this
* 2020/8/14 15:46
* by 991399725@qq.com
*/
public function add($number)
{
$this->result = bcadd($this->result, $number, $this->scale);
return $this;
}
/**
* 精确计算:减
* @param $number
* @return $this
* 2020/8/14 15:46
* by 991399725@qq.com
*/
public function sub($number)
{
$this->result = bcsub($this->result, $number, $this->scale);
return $this;
}
/**
* 精确计算:乘
* @param $number
* @return $this
* 2020/8/14 15:46
* by 991399725@qq.com
*/
public function mul($number)
{
$this->result = bcmul($this->result, $number, $this->scale);
return $this;
}
/**
* 精确计算:除
* @param $number
* @return $this
* 2020/8/14 15:46
* by 991399725@qq.com
*/
public function div($number)
{
$this->result = bcdiv($this->result, $number, $this->scale);
return $this;
}
/**
* 获取计算结果
* @return float
* 2020/8/14 15:59
* by 991399725@qq.com
*/
public function getResult()
{
return floatval($this->result);
}
}
//调用方法
//保留两位小数的方式精确计算
$accuracyCal = new AccuracyCal(2);
//以下代表表达式:0.1 + 2 - 1.1
$result = $accuracyCal->number(0.1)->add(2)->sub(1.1)->getResult();
注:请自行调整好加减乘除运算的优先级。
如果不当,欢迎指正!