Latest web development tutorials

PHP round () function

PHP Math Reference PHP Math Reference

Examples

Floating-point rounding:

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

Running instance »

Definition and Usage

round () function of the floating point rounding.

Tip: To rounded up to the nearest integer, see ceil () function.

Tip: To be rounded down to the nearest integer, see floor () function.


grammar

round( number,precision,mode );

参数 描述
number 必需。规定要舍入的值。
precision 可选。规定小数点后的尾数。默认是 0。
mode 可选。规定表示舍入模式的常量:
  • PHP_ROUND_HALF_UP - 默认。遇到 .5 的情况时向上舍入 numberprecision 小数位。舍入 1.5 到 2,舍入 -1.5 到 -2。
  • PHP_ROUND_HALF_DOWN - 遇到 .5 的情况时向下舍入 numberprecision 小数位。舍入 1.5 到 1,舍入 -1.5 到 -1。
  • PHP_ROUND_HALF_EVEN - 遇到 .5 的情况时取下一个偶数值舍入 numberprecision 小数位。
  • PHP_ROUND_HALF_ODD - 遇到 .5 的情况时取下一个奇数值舍入 numberprecision 小数位。

technical details

return value: After rounding the value.
Return type: Float
PHP version: 4+
PHP Update Log: PHP 5.3: Added mode parameter.


Examples s

More examples

Example 1

Figures rounded to two decimal places:

<?php
echo(round(4.96754,2) . "<br>");
echo(round(7.045,2) . "<br>");
echo(round(7.055,2));
?>

Running instance »

Example 2

Constant use of rounded numbers:

<?php
echo(round(1.5,0,PHP_ROUND_HALF_UP) . "<br>");
echo(round(-1.5,0,PHP_ROUND_HALF_UP) . "<br>");

echo(round(1.5,0,PHP_ROUND_HALF_DOWN) . "<br>");
echo(round(-1.5,0,PHP_ROUND_HALF_DOWN) . "<br>");

echo(round(1.5,0,PHP_ROUND_HALF_EVEN) . "<br>");
echo(round(-1.5,0,PHP_ROUND_HALF_EVEN) . "<br>");

echo(round(1.5,0,PHP_ROUND_HALF_ODD) . "<br>");
echo(round(-1.5,0,PHP_ROUND_HALF_ODD));
?>

Running instance »


PHP Math Reference PHP Math Reference