PHP Round Function: Rounding Numbers Guide

In PHP, you can use the round() function to perform rounding. The syntax for the round() function is as follows:

round(float $num, int $precision = 0, int $mode = PHP_ROUND_HALF_UP): float

其中的参数$num是需要进行四舍五入的数字,$precision是指保留几位小数,$mode是指定四舍五入的方式,默认是PHP_ROUND_HALF_UP,即小数部分为0.5时采用向上舍入的方式。

For example, rounding the decimal 3.14159 to two decimal places:

echo round(3.14159, 2); // 输出:3.14

If you need to use a different rounding method, you can specify it in the $mode parameter, for example:

  1. PHP_ROUND_HALF_UP: When rounding, if the decimal part is 0.5, it will be rounded up.
  2. When rounding, PHP_ROUND_HALF_DOWN rounds down if the decimal part is 0.5.
  3. PHP_ROUND_HALF_EVEN: When rounding, if the decimal portion is 0.5, it is rounded to the nearest even number.
  4. When rounding numbers with PHP_ROUND_HALF_ODD, if the decimal part is 0.5, it will be rounded to the nearest odd number.

For example, round the decimal 3.5 to the nearest whole number using the rounding up method.

echo round(3.5, 0, PHP_ROUND_HALF_UP); // 输出:4
bannerAds