php 价钱计算,php公式计算
1 通過evel計算公式 注意浮點數運算
eval — 把字符串作為PHP代碼執行
$data = [
'A1' => 100,
'A2' => 200,
'A3' => 300,
'A4' => 400,
'B1' => 101,
'B2' => 201,
'B3' => 301,
'B4' => 400,
];
foreach ($data as $index => $item) {
define($index, $item);
}
$amount = 0;
$formula = "A1 + A3 + A4 + B2 * (B1 + B3)";
$result = eval("return $formula; ");
var_dump($result);
2 通過bc函數實現 任意精度運算
bcadd — 2個任意精度數字的加法計算
bccomp — 比較兩個任意精度的數字
bcdiv — 2個任意精度的數字除法計算
bcmod — 對一個任意精度數字取模
bcmul — 2個任意精度數字乘法計算
bcpow — 任意精度數字的乘方
bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
bcscale — 設置所有bc數學函數的默認小數點保留位數
bcsqrt — 任意精度數字的二次方根
bcsub — 2個任意精度數字的減法
/**
* 公式計算
* @return mixed|null|string|string[]
*/
function bc()
{
bcscale(3);
$argv = func_get_args();
$string = str_replace(' ', '', '(' . $argv[0] . ')');
$string = preg_replace_callback('/\$([0-9\.]+)/', function ($matches) {
return '$argv[$1]';
}, $string);
while (preg_match('/(()?)\(([^\)\(]*)\)/', $string, $match)) {
while (preg_match('/([0-9\.]+)(\^)([0-9\.]+)/', $match[3], $m) || preg_match('/([0-9\.]+)([\*\/\%])([0-9\.]+)/', $match[3], $m) || preg_match('/([0-9\.]+)([\+\-])([0-9\.]+)/', $match[3], $m)) {
switch ($m[2]) {
case '+':
$result = bcadd($m[1], $m[3]);
break;
case '-':
$result = bcsub($m[1], $m[3]);
break;
case '*':
$result = bcmul($m[1], $m[3]);
break;
case '/':
$result = bcdiv($m[1], $m[3]);
break;
case '%':
$result = bcmod($m[1], $m[3]);
break;
case '^':
$result = bcpow($m[1], $m[3]);
break;
}
$match[3] = str_replace($m[0], $result, $match[3]);
}
if (!empty($match[1]) && function_exists($func = 'bc' . $match[1])) {
$match[3] = $func($match[3]);
}
$string = str_replace($match[0], $match[3], $string);
}
return $string;
}
//$ret = bc("2006 - 2005.98");
$ret = bc("(92 + (5 + 5) * 27 / 3) - (93 - 12*3 ) / (4 + 26)");
var_dump($ret);
總結
以上是生活随笔為你收集整理的php 价钱计算,php公式计算的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: eclipse+tomcat开发web程
- 下一篇: apache添加支持php的模块,配置A