Search code examples
phproundingfloor

Use round or floor depending the number after the comma


What would be the solution to have:

7.1 => 7
7.5 => 7
7.8 => 8

So I need to round number or floor depending on the number after the comma.

How to do that?

Thanks.


Solution

  • You should be able to use the constant, PHP_ROUND_HALF_DOWN, to have the round function round down when it is half way.

    echo round(7.1, 0, PHP_ROUND_HALF_DOWN) . "\n";
    echo round(7.5, 0, PHP_ROUND_HALF_DOWN) . "\n"; 
    echo round(7.8, 0, PHP_ROUND_HALF_DOWN) . "\n";
    

    Output:

    7
    7
    8
    

    From the manual:

    Round val down to precision decimal places towards zero, when it is half way there. Making 1.5 into 1 and -1.5 into -1.

    PHP Demo: https://eval.in/427706