在PHP中精确地舍入和舍入分数的函数,有没有更好的方法呢?

时间:2011-09-20 20:34:44

标签: php function math

我在php.net上找到了这个代码,它适用于我的round_up部分..

function round_up($value, $precision = 0) { 
 if (!empty($value)) {
 $sign = (0 <= $value) ? +1 : -1; 
 $amt = explode('.', $value); 
 $precision = (int) $precision; 
 if (strlen($amt[1]) > $precision) { 
     $next = (int) substr($amt[1], $precision); 
     $amt[1] = (float) (('.'.substr($amt[1], 0, $precision)) * $sign); 
     if (0 != $next) { 
         if (+1 == $sign) { 
             $amt[1] = $amt[1] + (float) (('.'.str_repeat('0', $precision - 1).'1') * $sign); 
         } 
     } 
 } 
 else { 
     $amt[1] = (float) (('.'.$amt[1]) * $sign); 
 } 
 return $amt[0] + $amt[1]; 
 }
 else {echo 'error';} 
 }

添加了几个减去..来获得这个......

function round_down($value, $precision = 0) { 
 if (!empty($value))  {
 $sign = (0 <= $value) ? +1 : -1; 
 $amt = explode('.', $value); 
 $precision = (int) $precision; 
 if (strlen($amt[1]) > $precision) { 
     $next = (int) substr($amt[1], $precision); 
     $amt[1] = (float) (('.'.substr($amt[1], 0, $precision)) * $sign); 
     if (0 != $next) { 
         if (-1 == $sign) { 
             $amt[1] = $amt[1] - (float) (('.'.str_repeat('0', $precision - 1).'1') * $sign); 
         } 
     } 
 } 
 else { 
     $amt[1] = (float) (('.'.$amt[1]) * $sign); 
 } 
 return $amt[0] + $amt[1]; 
 }
 else {echo 'error';}
 } 

有没有更好的方法呢? (我只要求它为正小数)目前大多数情况下它没有太多故障。

$azd = 0.0130; 

$azd1 = number_format(round_up($azd,2),4);
$azd2 = number_format(round_down($azd,2),4);
$azd3 = number_format(round_up($azd,1),4);
$azd4 = number_format(round_down($azd,1),4);

echo 'Round_up = '.$azd1.'<br>'; // 0.0200
echo 'Round_down = '.$azd2.'<br>'; // 0.0100
echo 'Round_up = '.$azd3.'<br>';    // 0.1000
echo 'Round_down = '.$azd4.'<br>';  // 0.0000

3 个答案:

答案 0 :(得分:6)

function round_up($value, $precision=0) {
    $power = pow(10,$precision);
    return ceil($value*$power)/$power;
}
function round_down($value, $precision=0) {
    $power = pow(10,$precision);
    return floor($value*$power)/$power;
}

答案 1 :(得分:1)

function round_up($float,$mod) {
    return ceil($float * pow(10,$mod)) / pow(10,$mod);
}
function round_down($float,$mod=0) {
    return floor($float * pow(10,$mod)) / pow(10,$mod);
}

答案 2 :(得分:0)

以上答案对我不起作用,我是从 PHP Ceil and Floor to the nearest 100 with rounding

得到的
function ceiling($number, $significance) {
   if ($significance != null) {
      return (is_numeric($number) && is_numeric($significance) ) ? (ceil($number / $significance) * $significance) : $number;
   } else {
      return $number;
   }
}

function flooring($number, $significance) {
   if ($significance != null) {
      return (is_numeric($number) && is_numeric($significance) ) ? (floor($number / $significance) * $significance) : $number;
   } else {
      return $number;
   }
}