Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 45 / 68

Rounding Numbers (floor, ceil, round)

In this lesson you will learn the difference between floor, ceil, and round so you can pick the right one for the job. This is for anyone searching for "PHP round down round up round half".

floor() rounds down, ceil() rounds up, and round() rounds to nearest. "Shave it down", "push it up", and "go to whichever is closer" are useful mental labels.

The sample code shows floor() turning 3.7 into 3, ceil() turning 3.2 into 4, and round() turning 3.5 into 4. Try each one with other numbers to see how it reacts.

A common stumbling block for beginners is that all three return a floating-point number. If you want an integer you may need an extra (int) cast, and carrying on with an unexpected type is a source of bugs.

The choice changes your results, so match it to the purpose. PHP's round() also takes a second argument for the number of decimal places, giving you fine control.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)