round()模式ROUND_HALF_DOWN,PHP 5.2.17

rag*_*lka 3 php mode rounding

我需要在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, '.', '' );
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ber 6

只需转换为字符串并返回即可作弊:

$num = 1.895;

$num = (string) $num;

if (substr($num, -1) == 5) $num = substr($num, 0, -1) . '4';

$num = round(floatval($num), 2);
Run Code Online (Sandbox Code Playgroud)

编辑:

在这里你有它的功能形式:

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);
}
Run Code Online (Sandbox Code Playgroud)