What is the usage of the round function in PHP?
The round() function in PHP is used to round a floating-point number to the nearest integer.
Syntax of functions:
round(float $number, int $precision = 0, int $mode = PHP_ROUND_HALF_UP): float|int
Explanation of parameters.
- $number: A floating-point number that must be rounded to the nearest whole number.
- $precision: Optional, can specify the number of decimal places, default is 0, indicating rounding to the nearest whole number.
- $mode: Optional parameter that specifies the rounding mode, defaulting to PHP_ROUND_HALF_UP, which means rounding up. Other optional modes include PHP_ROUND_HALF_DOWN (rounding down), PHP_ROUND_HALF_EVEN (rounding up if the discarded part is 0.5 and the previous digit is odd, rounding down if it’s even), and PHP_ROUND_HALF_ODD (rounding up if the discarded part is 0.5 and the previous digit is even, rounding down if it’s odd).
Return value: the rounded result, in either floating-point or integer type.
“Could you please explain this to me one more time?”
echo round(3.4); // 输出:3
echo round(3.5); // 输出:4
echo round(3.6); // 输出:4
echo round(3.14159, 2); // 输出:3.14,保留两位小数
echo round(3.14559, 2); // 输出:3.15,保留两位小数
echo round(3.5, 0, PHP_ROUND_HALF_DOWN); // 输出:3,向下舍入
echo round(3.5, 0, PHP_ROUND_HALF_EVEN); // 输出:4,根据奇偶性舍入
Note: The results returned by the round() function may not always be accurate, due to the way floating-point numbers are represented in computers. For more precise calculations, consider using other related functions such as number_format() or functions within the bcmath extension.