Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round() mode ROUND_HALF_DOWN with PHP 5.2.17

Tags:

php

rounding

mode

I need to simulate ROUND_HALF_DOWN mode in PHP 5.2.17 - I cannot upgrade the server's PHP version. Any ideas how to achieve this?

The basic idea is that 1.895 becomes 1.89, not 1.90 like it usually does with round().

EDIT: This function seems to do the trick:

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, '.', '' );
}
like image 495
ragulka Avatar asked Apr 17 '26 03:04

ragulka


1 Answers

You can cheat by simply converting to a string and back:

$num = 1.895;

$num = (string) $num;

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

$num = round(floatval($num), 2);

EDIT:

Here you have it in function form:

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);
}
like image 107
Joseph Silber Avatar answered Apr 18 '26 17:04

Joseph Silber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!