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;
}