The round()
function rounds a floating-point number to the nearest integer.
PHP round() function has following syntax.
float round ( float num [, int precision] )
Parameter | Is Required | Description |
---|---|---|
number | Required. | Value to round |
precision | Optional. | Number of decimal digits to round to. Default is 0 |
mode | Optional. | Rounding mode: |
The rounding mode value can the one of the following.
Item | Value |
---|---|
Return Value: | The rounded value |
Return Type: | Float |
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.
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.
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.
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.