我有下一个平均代码。
function array_average2(){
$args = func_get_args();
if(isset($args[0])){
if(is_array($args[0])){
$ret = (array_sum($args[0]) / count($args[0]));
}else{
$ret = (array_sum($args) / func_num_args());
}
}else{
$ret = 0;
}
$ret2=0.01 * (int)($ret*100);
return $ret2;
}
i need php round to rezult next:
$ret=1.23 - i need 1
$ret=6.23 - i need 6
$ret=6.70 - i need 7
$ret=5.50 - i need 5.50
$ret=5.49 - i need 5
结论 如果十进制在 0.50 旁边是下一个值,否则是前一个,但如果它是固定的 0.50 到 stai。 5+6=5.50.. 不要改变
充分利用 PHP 中的round()
并应用此逻辑
function array_average2(){
$args = func_get_args();
if(isset($args[0])){
if(is_array($args[0])){
$ret = (array_sum($args[0]) / count($args[0]));
}else{
$ret = (array_sum($args) / func_num_args());
}
}else{
$ret = 0;
}
$ret2=0.01 * (int)($ret*100);
$str = strval($ret);
if(strpos($str,'.50')!==false)
{
return $ret;
}
else
{
return round($ret2);
}
}
可能不是最好的,但它应该可以工作:
$string = (string)$ret;
if (substr($string, -3) != '.50') {
$ret = round($ret);
}
或
$string = (string)$ret;
if (strrpos($string, '.50') !== 0) {
$ret = round($ret);
}