This short tutorial will cover how to use the PHP floor() function to round numbers DOWN – and provide some code examples.
The PHP floor() function rounds a number down (and only down!) to the nearest integer.
To round a number up to the nearest integer, use the ceil() function instead.
To round a number normally, or for more options when rounding a number, use the round() function.
PHP floor() Function Syntax
The syntax for the PHP floor() function is as follows:
floor($NUMBER)
Note that:
- $NUMBER is the float or integer number you wish to perform the floor() operation on
- floor() will return a float type number regardless of the type of number passed to it
- The returned number will still be a whole integer – the float type is only used because it supports storing a larger range of numbers
- floor() will return the next lowest whole number – NOT the next number closest to 0
- This means negative numbers will be rounded DOWN
Code Examples
The floor() function is pretty simple, so the examples are pretty simple, too!
Below, various positive and negative numbers are passed to the PHP floor() function so that you can see the results:
echo floor(3); // 3 echo floor(7.1); // 7 echo floor(5.9999); // 5 echo floor(-2.5); // -3 echo floor(0); // 0
…The result of each floor() operation will be printed using the echo command (and the result is also shown in the code as a comment following each line).
The floor() function can be helpful for things like pagination or dividing up quantities of items that cannot exist in fractions (e.g., if dividing a group of students to be placed into classes, you can’t have 5.1 students unless something has gone very, very wrong).