PHP Tutorial - PHP round() Function






Definition

The round() function rounds a floating-point number to the nearest integer.

Syntax

PHP round() function has following syntax.

float round ( float num [, int precision] )

Parameter

ParameterIs Required Description
number Required.Value to round
precision Optional. Number of decimal digits to round to. Default is 0
modeOptional. Rounding mode:

The rounding mode value can the one of the following.

  • PHP_ROUND_HALF_UP - Default. Rounds number up to precision decimal, when it is half way there. Rounds 1.5 to 2 and -1.5 to -2
  • PHP_ROUND_HALF_DOWN - Round number down to precision decimal places, when it is half way there. Rounds 1.5 to 1 and -1.5 to -1
  • PHP_ROUND_HALF_EVEN - Round number to precision decimal places towards the next even value
  • PHP_ROUND_HALF_ODD - Round number to precision decimal places towards the next odd value




Return

Item Value
Return Value:The rounded value
Return Type:Float

Note

To round a number UP to the nearest integer, use the ceil() function.

To round a number DOWN to the nearest integer, use the floor() function.

Example

If a number is exactly halfway between two integers, round() will always round up. If you provide an integer, nothing will happen.


<?PHP//from  w w  w. j  a va2 s .c om
$number = round(11.1); // 11 
print $number;
print("\n");
$number = round(11.9); // 12 
print $number;
print("\n");
$number = round(11.5); // 12 
print $number;
print("\n");
$number = round(11); // 11 
print $number;
print("\n");
?>

The code above generates the following result.





Example 2

You can also provide the number of decimal places to round to:


<?PHP//from www.j a  va2s . co  m
$a = round(4.4999); // 4 
print $a;
print("\n");
$b = round(4.123456, 3); // 4.123 
print $b;
print("\n");
$c = round(4.12345, 4); // 4.1235 
print $c;
print("\n");
$d = round(1000 / 160); // 6 
print $d;
?>

The code above generates the following result.

Example 3

Round numbers using the rounding mode constants:


<?php// www  . ja  va2s . c  om
echo(round(1.5,0,PHP_ROUND_HALF_UP) . "\n");
echo(round(-1.5,0,PHP_ROUND_HALF_UP) . "\n");

echo(round(1.5,0,PHP_ROUND_HALF_DOWN) . "\n");
echo(round(-1.5,0,PHP_ROUND_HALF_DOWN) . "\n");

echo(round(1.5,0,PHP_ROUND_HALF_EVEN) . "\n");
echo(round(-1.5,0,PHP_ROUND_HALF_EVEN) . "\n");

echo(round(1.5,0,PHP_ROUND_HALF_ODD) . "\n");
echo(round(-1.5,0,PHP_ROUND_HALF_ODD));
?>

The code above generates the following result.