Last Updated:

Round function in php with example


In some cases, the site may require automatic rounding of a number to an integer up or down. For example, we need the price to be a multiple of 100 or 50 rubles in the product catalog. Then the php functions come to the rescue: round, ceil and floor.

Round function in PHP

Rounding to an integer

You can round the number up or down. The ceil and floor functions cope with this.

To greater importance

$a = 1,234;

echo ceil ($a); the screen will show 2

To a lower value

$a = 3,2;

echo floor ($a); see 3

With the number of decimal places

Use the round function when you want to specify the precision of rounding a number with a period. It is written as follows:

round ( $a, [number of decimal places to be rounded] );

Sample php code:

$a = 1,23432;

echo round ($a, 2); the screen will have a number with two decimal places – 1.23

Also, this function allows the use of the third parameter. These are constants PHP_ROUND_HALF that expand the possibilities of use. _UP and _DOWN added at the end give the programmer the ability to specify the accuracy of rounding in controversial moments. For example, if a random number is 2.5, it can be converted to either 2 or 3.

_EVEN rounds the number, given the decimal places, to an even value.

_ODD has a similar effect, but makes the number odd.

Otherwise, such manipulations are also called bank rounding.

Multiples of dozens, hundreds, thousands


If you do not just want to round the number of decimal places, but make the number a multiple of a certain value, you can use round, specifying the second parameter negative. But, as practice shows, accurate solutions are not always obtained, so we recommend using multiplication and division.

Example: you need to round $a = 208 to tens upwards to get 210. To do this, we write:

echo ceil ($a / 10) *10;

First, an action in parentheses will be performed, during which you will get 20.8. Next, rounding to a larger 21 will work. After 21, it is multiplied by 10 and the required value is obtained. For rounding, a multiple of hundreds and thousands of 10 is changed to 100 and 1000.