Search code examples
phproundingprecisionfloating-point-precision

round() returns redundant amount of decimals


I've written many PHP applications and have just stumbled upon a weird scenario. The round function doesn't seem to be working in a very complex set of code. I've tried many different things before calling round, but this just doesn't work. The function returns 0.56000000000000001 when given round($val,2), with $val=0.5600. This should obviously return 0.56.

I've changed my code to use number_format($val,2,',',''). This seems to have solved the issue, but now I'm 2nd guessing all my other code.

Should I replace round with number_format everywhere? Has anyone had similar errors with round?

Also to note this seems to be linked with PhpExcel which is used in this instance. https://github.com/PHPOffice/PHPExcel/issues/237


Solution

  • There is no need to replace round with number_format. You could use round with the flag to round down.

    Choose what is best for the application.

    • Are you rounding a float? Use round
    • Are you wanting to format a number and group by thousands? Use number_format

    <?php 
    $number = '0.5600'; 
    echo round((float)$number, 2, PHP_ROUND_HALF_DOWN);
    

    https://eval.in/297781