Integer and Float Functions

Apart from the basic operators +, -, /, *, and %, PHP provides the usual array of mathematical library functions. In this section, we present some of the library functions that are used with integer and float numbers.

Absolute Value

The absolute value of an integer or a float can be found with the abs( ) function:

integer abs(integer number)
float abs(float number)

The following examples show the result of abs( ) on floats and integers:

echo abs(-1);       // prints 1
echo abs(1);        // prints 1
echo abs(-145.89);  // prints 145.89
echo abs(145.89);   // prints 145.89

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

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


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

Get Web Database Applications with PHP, and MySQL now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.