Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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().

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page