How to implement php rounding to two decimal places

藏色散人
Release: 2023-03-03 19:08:01
Original
5614 people have browsed it

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.

How to implement php rounding to 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);
Copy after login

Method two, (not complete 0)

echo round($num,2);
Copy after login

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
Copy after login

It can be seen that the numbers are not rounded

Then the ultimate solution appears

echo sprintf("%.2f", round($n,2));
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!