PHP 浮点数计算问题

<?php
/**
 * 任意两个数的数学计算(+、-、*、/)支持扩展其他运算符 详细请阅读 PHP BC数学函数
 * @param float|int $left_operand  左操作数
 * @param float|int $right_operand 右操作数
 * @param string $operator 运算符
 * @param int $scale 结果保留小数点精度
 * @return float
 */
function float_calculate($left_operand,$right_operand,$operator='+',$scale=2){
    if(!$left_operand || is_numeric($left_operand) || !$right_operand || is_numeric($right_operand)) return false;
	switch($operator){
		case '-':
			$func='bcsub';
			break;
		case '*':
			$func='bcmul';
			break;
		case '/':
			$func='bcdiv';
			break;
		default:
			$func='bcadd';
			break;
	}
	return $func($left_operand,$right_operand,$scale); 
}


/**
 * 多个数字的数学计算(+、-、*、/) 支持扩展其他运算符 详细请阅读 PHP BC数学函数
 * @param array $params  要计算的数字数组按顺序依次用运算符连接计算 例 [10,5,2] => 10-5-2
 * @param string $operator 运算符
 * @param int $scale 结果保留小数点精度
 * @return float
 */
function more_float_calculate($params,$operator='+',$scale=2){
    if(!is_array($params) || count($params)<2) return false;
    foreach($params as $item){
        if(is_numeric($item)) return false;
    }
	switch($operator){
		case '-':
			$func='bcsub';
			break;
		case '*':
			$func='bcmul';
			break;
		case '/':
			$func='bcdiv';
			break;
		default:
			$func='bcadd';
			break;
    }
    $length=count($params);
    $result=$func($params[0],$params[1],$scale);
    if($length>2){
        for($i=2;$i<$length;$i++){
            $result=$func($result,$params[$i],$scale);
        }
    }
	return $result; 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章