Home » Programming » PHP » Php Floor

Rounding Numbers Down with the PHP floor() Function, with Examples

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

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

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment