PFinal\Wechat\Service\PayService::calc PHP Method

calc() public static method

var_dump(floor((0.1 + 0.7) * 10)); // 7 var_dump(floor(\Rain\self::calc(\Rain\self::calc(0.1, 0.7, '+'), 10, '*'))); // 8
public static calc ( string $a, string $b, string $operator, integer $scale = 2 ) : string | integer
$a string
$b string
$operator string 操作符 支持: "+"、 "-"、 "*"、 "/"、 "comp"
$scale integer 小数精度位数,默认2位
return string | integer 加减乖除运算,返回string。比较大小时,返回int(相等返回0, $a大于$b返回1, 否则返回-1)
    public static function calc($a, $b, $operator, $scale = 2)
    {
        $scale = (int) $scale;
        $scale = $scale < 0 ? 0 : $scale;
        $bc = array('+' => 'bcadd', '-' => 'bcsub', '*' => 'bcmul', '/' => 'bcdiv', 'comp' => 'bccomp');
        if (!array_key_exists($operator, $bc)) {
            throw new \Exception('operator error');
        }
        if (function_exists($bc[$operator])) {
            $fun = $bc[$operator];
            return $fun($a, $b, $scale);
        }
        switch ($operator) {
            case '+':
                $c = $a + $b;
                break;
            case '-':
                $c = $a - $b;
                break;
            case '*':
                $c = $a * $b;
                break;
            case '/':
                $c = $a / $b;
                break;
            case 'comp':
                // 按指定精度,去掉小数点,放大为整数字符串
                $a = ltrim(number_format((double) $a, $scale, '', ''), '0');
                $b = ltrim(number_format((double) $b, $scale, '', ''), '0');
                $a = $a === '' ? '0' : $a;
                $b = $b === '' ? '0' : $b;
                if ($a === $b) {
                    return 0;
                }
                return $a > $b ? 1 : -1;
            default:
                throw new \Exception('operator error');
        }
        $c = number_format($c, $scale, '.', '');
        return $c;
    }