Home  >  Article  >  Backend Development  >  How to implement php rounding to two decimal places

How to implement php rounding to two decimal places

藏色散人
藏色散人Original
2020-08-05 09:13:095665browse

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);

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!

Statement:
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