Search code examples
phpdecimalroundingprecisionaccounting

PHP Round up long float to two decimals in accounting


Say you have this number 562.9444445 and you want to round it up to 2 decimals. Now I would say that the result would be 562.95 as the 5 is carried up from the tail. No?

Well, the PHP round function does not work like that. It will just check the next digit, in this case, the 3rd and return 562.94.

I've tried with all the constant values of the $mode argument but none of them return the correct result.

I'm curious to know if anyone has encountered this and if there is a more precise rounding function that could be used.

I've found this comment that can be useful but I think/hope something else might exist.

Demo

<?php
$value = 562.9445;

echo round($value,1)."\n"; // return 562.9 (correctly)
echo round($value,2)."\n"; // return 562.94 (wrong)
echo round($value,3)."\n"; // return 562.945 (correctly)

Solution

  • you can use this function

    <?php
    function round_up ( $value, $precision ) { 
        $pow = pow ( 10, $precision ); 
        return ( ceil ( $pow * $value ) + ceil ( $pow * $value - ceil ( $pow * $value ) ) ) / $pow; 
    } 
    $value = 562.9445;
    
    echo round_up ($value,1)."\n"; // return 563  
    echo round_up ($value,2)."\n"; // return 562.95 
    echo round_up ($value,3)."\n"; // return 562.945
    

    if you need to use round function there is some options that dont siuts to you:

    <!DOCTYPE html>
    <html>
    <body>
    
    <?php
    $value = 562.9445;
    echo(round($value,1,PHP_ROUND_HALF_UP) . "<br>");
    echo(round($value ,2,PHP_ROUND_HALF_UP) . "<br>");
    echo(round($value ,3,PHP_ROUND_HALF_UP) . "<br>");
    echo ("<hr>");
    
    echo(round($value ,1,PHP_ROUND_HALF_DOWN) . "<br>");
    echo(round($value ,2,PHP_ROUND_HALF_DOWN) . "<br>");
    echo(round($value ,3,PHP_ROUND_HALF_DOWN) . "<br>");
    echo ("<hr>");
    echo(round($value ,1,PHP_ROUND_HALF_EVEN) . "<br>");
    echo(round($value ,2,PHP_ROUND_HALF_EVEN) . "<br>");
    echo(round($value ,3,PHP_ROUND_HALF_EVEN) . "<br>");
    echo ("<hr>");
    echo(round($value ,1,PHP_ROUND_HALF_ODD) . "<br>");
    echo(round($value ,2,PHP_ROUND_HALF_ODD) . "<br>");
    echo(round($value ,3,PHP_ROUND_HALF_ODD));
    ?>
    
    </body>
    </html>
    

    output:

    562.9
    562.94
    562.945
    562.9
    562.94
    562.944
    562.9
    562.94
    562.944
    562.9
    562.94
    562.945