PHP Function Reference

PHP round() Function



The PHP round() function returns the rounded value of the number to specified precision. In special cases it returns the following:

  • If the argument is NAN, the result is NAN.
  • If the argument is infinity, the result is equal to the argument.

Syntax

round(number, precision, mode)

Parameters

number Required. Specify a floating point value to be rounded.
precision Optional. Specify the number of decimal digits to round to. Default is 0.
mode Optional. Specify one of the following constants to specify the mode in which rounding occurs:
  • PHP_ROUND_HALF_UP: Default. Rounds number away from zero when it is half way.
  • PHP_ROUND_HALF_DOWN: Rounds number towards zero when it is half way.
  • PHP_ROUND_HALF_EVEN: Rounds number towards the nearest even value when it is half way.
  • PHP_ROUND_HALF_ODD: Rounds number towards the nearest odd value when it is half way.

Return Value

Returns the rounded value of the number to specified precision.

Example:

In the example below, round() function returns the value of argument rounded to zero decimal digits.

<?php
echo "round(10.3) = ".round(10.3)."\n";
echo "round(10.5) = ".round(10.5)."\n";
echo "round(10.7) = ".round(10.7)."\n";
echo "round(-9.3) = ".round(-9.3)."\n";
echo "round(-9.5) = ".round(-9.5)."\n";
echo "round(-9.7) = ".round(-9.7)."\n";
echo "round(INF) = ".round(INF)."\n";
echo "round(-INF) = ".round(-INF)."\n";
echo "round(NAN) = ".round(NAN)."\n";
?>

The output of the above code will be:

round(10.3) = 10
round(10.5) = 11
round(10.7) = 11
round(-9.3) = -9
round(-9.5) = -10
round(-9.7) = -10
round(INF) = INF
round(-INF) = -INF
round(NAN) = NAN

Example:

The example below illustrates on optional parameters of round() function.

<?php
//using precision parameter
echo "M_PI = ".M_PI."\n";
echo "round(M_PI, 2) = ".round(M_PI, 2)."\n";
echo "round(M_PI, 3) = ".round(M_PI, 3)."\n";

//using modes with precision parameter
echo "\nround(10.5, 0, PHP_ROUND_HALF_UP) = "
     .round(10.5, 0, PHP_ROUND_HALF_UP)."\n";
echo "round(10.5, 0, PHP_ROUND_HALF_DOWN) = "
     .round(10.5, 0, PHP_ROUND_HALF_DOWN)."\n";
echo "round(10.5, 0, PHP_ROUND_HALF_EVEN) = "
     .round(10.5, 0, PHP_ROUND_HALF_EVEN)."\n";
echo "round(10.5, 0, PHP_ROUND_HALF_ODD) = "
     .round(10.5, 0, PHP_ROUND_HALF_ODD)."\n";
?>

The output of the above code will be:

M_PI = 3.1415926535898
round(M_PI, 2) = 3.14
round(M_PI, 3) = 3.142

round(10.5, 0, PHP_ROUND_HALF_UP) = 11
round(10.5, 0, PHP_ROUND_HALF_DOWN) = 10
round(10.5, 0, PHP_ROUND_HALF_EVEN) = 10
round(10.5, 0, PHP_ROUND_HALF_ODD) = 11

❮ PHP Math Reference