How to round a number in PHP?
In PHP, you can use the round() function to round a number.
The syntax of the round() function is as follows:
round(float $number, int $precision = 0, int $mode = PHP_ROUND_HALF_UP): float
In this case, $number represents the floating-point number to be rounded, $precision represents the number of decimal places to be retained, with a default of 0 indicating rounding to the nearest whole number, and $mode represents the rounding mode, with a default of PHP_ROUND_HALF_UP meaning rounding up.
Here are a few examples:
$number = 3.14159;
$rounded = round($number); // 四舍五入取整,默认保留0位小数
echo $rounded; // 输出:3
$rounded = round($number, 2); // 保留2位小数
echo $rounded; // 输出:3.14
$rounded = round($number, 0, PHP_ROUND_HALF_DOWN); // 向下取整
echo $rounded; // 输出:3
$rounded = round($number, 0, PHP_ROUND_HALF_EVEN); // 偶数位数时才进行四舍五入
echo $rounded; // 输出:3
Different rounding operations can be achieved by passing in different parameter values according to specific requirements.