【问题标题】:Php Round - aprox to decimalsPhp Round - 约小数
【发布时间】:2014-03-12 04:50:12
【问题描述】:

我有下一个平均代码。

    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..不要改变

【问题讨论】:

  • return (int)$ret + 0.5 === $ret ? $ret : round($ret);

标签: php rounding


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    可能不是最好的,但应该可以:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多