Home >Backend Development >PHP Problem >How to implement php rounding to two decimal places
How to implement PHP rounding to two decimal places: First create a PHP sample file; then pass "sprintf("%.2f", $num);" or "round($num,2);" The method implements rounding and retains two decimal places.
Recommended: "PHP Video Tutorial"
php rounds to two decimal places and automatically completes 0
It is very simple for php to round to two decimal places
Method one, (automatically complete 0)
echo sprintf("%.2f", $num);
Method two, (not complete 0)
echo round($num,2);
Recently, the project has encountered a problem. Method 1 is not good at rounding.
For example,
$num =1.785; echo sprintf("%.2f", $num); //结果1.78
It can be seen that the numbers are not rounded
Then the ultimate solution appears
echo sprintf("%.2f", round($n,2));
The above is the detailed content of How to implement php rounding to two decimal places. For more information, please follow other related articles on the PHP Chinese website!