我需要在PHP 5.2.17中模拟ROUND_HALF_DOWN模式-我无法升级服务器的PHP版本。有什么办法做到这一点吗?
基本思想是1.895变成1.89,而不是像round()那样通常是1.90。
编辑:这个函数似乎可以达到这个目的:
function nav_round($v, $prec = 2) {
// Seems to fix a bug with the ceil function
$v = explode('.',$v);
$v = implode('.',$v);
// The actual calculation
$v = $v * pow(10,$prec) - 0.5;
$a = ceil($v) * pow(10,-$prec);
return number_format( $a, 2, '.', '' );
}
您可以通过简单地转换为字符串并返回来欺骗:
$num = 1.895;
$num = (string) $num;
if (substr($num, -1) == 5) $num = substr($num, 0, -1) . '4';
$num = round(floatval($num), 2);
编辑:函数形式:
echo round_half_down(25.2568425, 6); // 25.256842
function round_half_down($num, $precision = 0)
{
$num = (string) $num;
$num = explode('.', $num);
$num[1] = substr($num[1], 0, $precision + 1);
$num = implode('.', $num);
if (substr($num, -1) == 5)
$num = substr($num, 0, -1) . '4';
return round(floatval($num), $precision);
}
在PHP 5.3之前,似乎最简单的方法是在所需的精度中从最后一个数字后面的数字减去1。因此,如果你有精度2,并希望1.995变成1.99,只需从数字中减去0.001,然后四舍五入。这将始终返回一个正确的四舍五入,除了一半的值将向下四舍五入而不是向上。
例二:
$num = 1.835;
$num = $num - .001; // new number is 1.834
$num = round($num,2);
echo $num;
四舍五入后的值现在是1.83
要获得另一种精度,只需调整减去1的位置。
Example2:
$num = 3.4895;
$num = $num - .0001; // new number is 3.4894
$num = round($num, 3);
echo $num;
四舍五入后的值现在是3.489
如果你想用一个函数来处理这个工作,下面的函数可以完成。
function round_half_down($num,$precision)
{
$offset = '0.';
for($i=0; $i < $precision; $i++)
{
$offset = $offset.'0';
}
$offset = floatval($offset.'1');
$num = $num - $offset;
$num = round($num, $precision);
return $num;
}
可以去掉0.5^p,其中p是精度,然后使用ceiling:
<?php
function round_half_down($v, $prec) {
$v = $v * pow(10,$prec) - 0.5;
return ceil($v) * pow(10,-$prec);
}
print round_half_down(9.5,0) . "'n";
print round_half_down(9.05,0) . "'n";
print round_half_down(9.051,0) . "'n";
print round_half_down(9.05,1) . "'n";
print round_half_down(9.051,1) . "'n";
print round_half_down(9.055,2) . "'n";
print round_half_down(1.896,2) . "'n";
?>
收益率:
$ php test.php
9
9
9
9
9.1
9.05
1.9
你会注意到,对于任何数字x <= p <= x.5,我们得到ceiling(p - 0.5) = x,对于所有x+1 => p> x.5,我们得到ceiling(p - 0.5) = x+1。这应该正是你想要的。
您可以使用preg_replace:
$string = '1.895';
$pattern = '/('d+).('d+)/e';
$replacement = "'''1'.'.'.((substr($string, -1) > 5) ? (substr('''2',0,2) + 1) : substr('''2',0,2))";
echo preg_replace($pattern, $replacement, $string);