PHP round() function
The round()
function in PHP rounds a floating-point number to the nearest integer. It can round up or down depending on the decimal value. By default, if the decimal portion is exactly 0.5, round()
will round up to the nearest even integer (this is known as "bankers' rounding"). You can also specify the number of decimal places to which you want to round.
Syntax:
- $value: The floating-point number you want to round.
- $precision: (optional) The number of decimal digits to round to. Default is
0
, which means it will return an integer. - $mode: (optional) Rounding mode, which can change how the function rounds numbers at the midpoint (e.g., 0.5). The default is
PHP_ROUND_HALF_UP
.
Example 1: Basic Rounding
Output:
Explanation: The number 4.4
is rounded down to 4
.
Example 2: Rounding Up
Output:
Explanation: In this case, 4.5
is rounded to the nearest even integer, which is 4
. (Bankers' rounding)
Example 3: Rounding Up to Even
Output:
Explanation: The number 5.5
is rounded up to 6
, following the same rounding rules.
Example 4: Specifying Decimal Places
Output:
Explanation: The number 3.14159
is rounded to two decimal places, resulting in 3.14
.
Example 5: Rounding a Negative Number
Output:
Explanation: The number -3.6
is rounded down to -4
because it is the nearest integer less than -3.6
.
Example 6: Using Different Rounding Modes
You can specify different rounding modes. The available modes are:
PHP_ROUND_HALF_UP
: Round towards the next higher integer.PHP_ROUND_HALF_DOWN
: Round towards the next lower integer.PHP_ROUND_HALF_EVEN
: Round to the nearest even integer (default).PHP_ROUND_HALF_ODD
: Round to the nearest odd integer.
Here's how to use a different mode:
Output:
Explanation: The number 2.5
is rounded down to 2
using the PHP_ROUND_HALF_DOWN
mode.
Key Points:
- The
round()
function is versatile and allows rounding to a specified number of decimal places. - It uses bankers' rounding by default, which can help to avoid bias in rounding in some cases.
- It can round both positive and negative numbers, providing results that fit typical rounding rules.
Overall, round()
is a useful function for handling numerical data where precision and correct rounding behavior are required.