Functions to Round up and Round down fractions with precision in PHP, any better way to do it?

a 夏天 提交于 2020-01-15 03:14:25

问题


I found this code on php.net which works for me for the round_up part..

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';} 
 }

Added a couple minus's.. to get this one...

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';}
 } 

Is there any better way to do it? (I only require it for positive decimals) Currently for the most part it works without much glitches..

$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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/7491434/functions-to-round-up-and-round-down-fractions-with-precision-in-php-any-better

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!