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:

round(float $value, int $precision = 0, int $mode = PHP_ROUND_HALF_UP): float
  • $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

<?php echo round(4.4); ?>

Output:

4

Explanation: The number 4.4 is rounded down to 4.

Example 2: Rounding Up

<?php echo round(4.5); ?>

Output:

4

Explanation: In this case, 4.5 is rounded to the nearest even integer, which is 4. (Bankers' rounding)

Example 3: Rounding Up to Even

<?php echo round(5.5); ?>

Output:

6

Explanation: The number 5.5 is rounded up to 6, following the same rounding rules.

Example 4: Specifying Decimal Places

<?php echo round(3.14159, 2); ?>

Output:

3.14

Explanation: The number 3.14159 is rounded to two decimal places, resulting in 3.14.

Example 5: Rounding a Negative Number

<?php echo round(-3.6); ?>

Output:

-4

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:

<?php echo round(2.5, 0, PHP_ROUND_HALF_DOWN); ?>

Output:

2

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.