PHP Round Float to Nearest Integer
In PHP, rounding a float to an integer is a common task achieved
using three built-in functions: round(),
ceil(), and floor(). This article explains how
each of these functions behaves, the key differences between them, and
provides clear code examples so you can choose the correct method for
your specific programming needs.
1. The round() Function
The round() function rounds a float to its nearest
integer based on standard mathematical rules. If the fractional part is
0.5 or higher, it rounds up; otherwise, it rounds down.
<?php
echo round(4.3); // Outputs: 4
echo round(4.6); // Outputs: 5
echo round(4.5); // Outputs: 5
// It also works with negative numbers
echo round(-4.5); // Outputs: -5
echo round(-4.3); // Outputs: -4
?>2. The ceil() Function
The ceil() (ceiling) function always rounds a float
up to the next highest integer. Even if the fractional part is
very small (like 0.1), the number is pushed up to the next
integer.
<?php
echo ceil(4.1); // Outputs: 5
echo ceil(4.9); // Outputs: 5
// Note how it behaves with negative numbers (moves towards zero)
echo ceil(-4.9); // Outputs: -4
?>3. The floor() Function
The floor() function always rounds a float down
to the next lowest integer. It discards the fractional part and lowers
the value to the previous whole number.
<?php
echo floor(4.9); // Outputs: 4
echo floor(4.1); // Outputs: 4
// Note how it behaves with negative numbers (moves away from zero)
echo floor(-4.1); // Outputs: -5
?>Summary of Differences
- Use
round()when you need standard mathematical rounding to the closest whole number. - Use
ceil()when you always need to round up to the next largest integer. - Use
floor()when you always need to round down to the next smallest integer.