2014-02-13 21 views
1

我有下一个平均代码。Php Round - aprox转换为小数

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到静态。 5 + 6 = 5.50 ..不改变

+0

'return(int)$ ret + 0.5 === $ ret? $ ret:round($ ret);' – raina77ow

回答

0

好利用round()在PHP和应用此逻辑

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); 
    } 
} 
+1

似乎工作,谢谢。 –

0

可能不是最好的,但它应该工作:

$string = (string)$ret; 

if (substr($string, -3) != '.50') { 
    $ret = round($ret); 
} 

OR

$string = (string)$ret; 

if (strrpos($string, '.50') !== 0) { 
    $ret = round($ret); 
}