Name

round()

Synopsis

    float round ( float num [, int precision] )

The round() function takes a floating-point number as its parameter and rounds it to the nearest integer to its current value. If a number is exactly halfway between two integers, round() will always round up. If you provide an integer, nothing will happen. For example:

    $number = round(11.1); // 11
    $number = round(11.9); // 12
    $number = round(11.5); // 12
    $number = round(11); // 11

You can also provide the number of decimal places to round to:

    $a = round(4.4999); // 4
    $b = round(4.123456, 3); // 4.123
    $c = round(4.12345, 4); // 4.1235
    $d = round(1000 / 160); // 6

The last example is a common situation encountered by people using round(). Imagine you were organizing a big trip to the countryside, and 1000 people signed up. You need to figure out how many buses you need to hire, so you take the number of people, 1000, and divide it by the capacity of your buses, 160, then round it to get a whole number. You find the result is 6.

Where is the problem? Well, the actual result of 1000/160 is 6.25—you need 6.25 buses to transport 1000 people, and you will only have ordered 6 because round() rounded toward 6 rather than 7, since it was closer. As you cannot order 6.5 buses, what do you do? The solution is simple: in situations like this, you use ceil().

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.