PHP has three main rounding functions.
| Function | Direction |
|---|---|
round() | To the nearest value |
floor() | Always down |
ceil() | Always up |
<?php
echo round(4.4) . "\n";
echo round(4.5) . "\n";
echo floor(4.9) . "\n";
echo ceil(4.1);
4
5
4
5
round(4.5) goes up. By default, PHP rounds halves away from zero, so -4.5 becomes -5.
Decimal places
The second argument is how many decimals to keep.
<?php
echo round(3.14159, 2) . "\n";
echo round(2.5, 0) . "\n";
echo round(1234.5678, 1);
3.14
3
1234.6
Negative precision
A negative number rounds to tens, hundreds and so on.
<?php
echo round(1234, -1) . "\n";
echo round(1234, -2) . "\n";
echo round(1950, -2);
1230
1200
2000
Return type is a float
round(), floor() and ceil() all return a float, even for a whole number. Use a cast or intval() if you need an integer.
<?php
var_dump(round(5.2));
var_dump((int) round(5.2));
float(5)
int(5)
Rounding modes
By default, halves round away from zero. You can ask for other behaviour with a third argument.
<?php
echo round(2.5, 0, PHP_ROUND_HALF_EVEN) . "\n"; // banker's rounding
echo round(3.5, 0, PHP_ROUND_HALF_EVEN) . "\n";
echo round(2.5, 0, PHP_ROUND_HALF_DOWN);
2
4
2
PHP 8.4 adds a RoundingMode enum with more modes, such as RoundingMode::TowardsZero. On older versions, use the PHP_ROUND_* constants.
Page counts: ceil()
How many pages for 47 results, 10 per page? You need to round up.
<?php
$results = 47;
$perPage = 10;
echo ceil($results / $perPage);
5
Displaying vs calculating
Rounding changes the stored value. If you only want to show two decimals, use number_format() and keep the full number for calculations. See Number Formatting.