Search code examples
phproundingfloor

How to round down to nearest whole decimal in PHP


Not sure if I've explained the question properly but below are some random examples of what I need to happen

20.39 to become 20.30

40.55 to become 40.50

9.22 to become 9.20


Solution

  • Use floor after multiplying by 10 and then divide by 10 again. To keep the second decimal place after rounding, use number_format.

    $values = [20.39,40.55,9.22];
    foreach ($values as $value) {
        echo number_format(floor($value * 10) / 10, 2);
    }
    

    Output:

    20.30
    40.50
    9.20