[Previous] [Contents] [Next]

Ceiling, Rounding and Floor

The ceil( ) and floor( ) functions can return the integer value above and below a fractional value, respectively:

float ceil(float value)
float floor(float value)
float round(float value)

The return type is a float because an integer may not be able to represent the result when a large value is passed as an argument. Consider the following examples:

echo ceil(27.3);   // prints 28
echo floor(27.3);  // prints 27
echo round(10.4);  // prints 10

ceil

ceil returns value rounded up to the next highest integer. The return value of ceil() is still of type float as the value range of float is usually bigger than that of integer.

float ceil ( float $value )

Examples:

echo ceil(3.3);       // 4
echo ceil(7.99);      // 8
echo ceil(-5.14444);  // -4

floor

floor returns the next lowest integer value by rounding down value.

float floor ( float $value )

Examples:

echo floor(3.3);      // 3
echo floor(7.99);     // 7
echo floor(-5.14444); // -5

Rounding

The round( ) function uses 4/5 rounding rules to round up or down a value to a given precision:

float round(float value [, integer precision])

Rounding by default is to zero decimal places, but the precision can be specified with the optional precision argument. The 4/5 rounding rules determine if a number is rounded up or down based on the digits that are lost due to the rounding precision. For example, 10.4 rounds down to 10, and 10.5 rounds up to 11. The following examples show rounding at various precisions:

echo round(10.4);           // prints 10
echo round(10.5);           // prints 11
echo round(2.40964, 3);     // prints 2.410
echo round(567234.56, -3);  // prints 567000
echo round(567234.56, -4);  // prints 570000

[Previous] [Contents] [Next]