Round floating point numbers:
<?php echo ( round ( 0 .60 ) . " <br> " ) ; echo ( round ( 0 .50 ) . " <br> " ) ; echo ( round ( 0 .49 ) . " <br> " ) ; echo ( round ( - 4 .40 ) . " <br> " ) ; echo ( round ( - 4 .60 ) ) ; ?>The round() function rounds floating point numbers.
Tip: To round up to the nearest integer, check out the ceil() function.
Tip: To round down to the nearest integer, check out the floor() function.
round( number,precision,mode );
parameter | describe |
---|---|
number | Required. Specifies the value to be rounded. |
precision | Optional. Specifies the number of digits after the decimal point. The default is 0, but it can also be a negative number. |
mode | Optional. Specifies constants representing rounding modes: PHP_ROUND_HALF_UP - Default. When encountering .5, round the number up to the decimal place of precision . Rounds 1.5 to 2 and -1.5 to -2. PHP_ROUND_HALF_DOWN - Round the number down to precision decimal places when encountering .5. Rounds 1.5 to 1 and -1.5 to -1. PHP_ROUND_HALF_EVEN - When encountering .5, take the next even value and round the number to precision decimal places. PHP_ROUND_HALF_ODD - When encountering .5, take the next odd value and round the number to precision decimal places. |
Return value: | The rounded value. |
---|---|
Return type: | Float |
PHP version: | 4+ |
PHP change log: | PHP 5.3: New mode parameter. |
Round numbers to two decimal places, set negative numbers:
<?php echo round ( 3 .4 ) ; // 3 echo round ( 3.5 ) ; // 4 echo round ( 3.6 ) ; // 4 echo round ( 3.6 , 0 ) ; // 4 echo round ( 1 .95583 , 2 ) ; // 1.96 echo round ( 1241757 , - 3 ) ; // 1242000 echo round ( 5 .045 , 2 ) ; // 5.05 echo round ( 5 .055 , 2 ) ; // 5.06 ?>Use constants to round numbers:
<?php echo round ( 9 .5 , 0 , PHP_ROUND_HALF_UP ) ; // 10 echo round ( 9 .5 , 0 , PHP_ROUND_HALF_DOWN ) ; // 9 echo round ( 9 .5 , 0 , PHP_ROUND_HALF_EVEN ) ; // 10 echo round ( 9 .5 , 0 , PHP_ROUND_HALF_ODD ) ; // 9 echo round ( 8 .5 , 0 , PHP_ROUND_HALF_UP ) ; // 9 echo round ( 8 .5 , 0 , PHP_ROUND_HALF_DOWN ) ; // 8 echo round ( 8 .5 , 0 , PHP_ROUND_HALF_EVEN ) ; // 8 echo round ( 8 .5 , 0 , PHP_ROUND_HALF_ODD ) ; // 9 ?>