PHP round()Function

PHP Math 参考手册PHP Math Reference Manual

Examples

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)); ?>

Run example »

Definition and Usage

The round() function rounds a floating-point number.

Tip:To round up to the nearest integer, see theceil()function.

Tip:To round down to the nearest integer, see thefloor()function.


Syntax

round(number,precision,mode);

Parameter Description
number Required. Specifies the value to round.
precision Optional. Specifies the number of decimal places. Default is 0; it can also be negative.
mode Optional. Specifies a constant that indicates the rounding mode:
  • PHP_ROUND_HALF_UP - Default. Rounds up when encountering .5numbertoprecisiondecimal places. Rounds 1.5 to 2, and -1.5 to -2.
  • PHP_ROUND_HALF_DOWN - Rounds down when encountering .5numbertoprecisiondecimal places. Rounds 1.5 to 1, and -1.5 to -1.
  • PHP_ROUND_HALF_EVEN - Rounds to the next even value when encountering .5numbertoprecisiondecimal places.
  • PHP_ROUND_HALF_ODD - Rounds to the next odd value when encountering .5numbertoprecisiondecimal places.

Technical Details

Return value: The rounded value.
Return type: Float
PHP version: 4+
PHP Changelog: PHP 5.3: Added the mode parameter.


实例s

More Examples

Example 1

Round numbers to two decimal places and 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 ?>

Example 2

Round numbers using constants:

<?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 ?>


PHP Math 参考手册PHP Math Reference Manual Other Extensions