Home > Article > Backend Development > Introduction to several methods of retaining two decimal places in PHP
1. Situation without rounding
For example, 3.149569 is taken to two decimal places, and the last two digits cannot be rounded off. Result: 3.14.
You can use the floor function
This function is rounding. For example, floor(4.66456) results in: 4 .
floor(9.1254) Result 9.
Therefore, to remove two decimal places, you need to multiply by 100 first, then round off, and then divide by 100, that is:
$a=floor(3.149569*100)/100
At this time, a bug will appear in floating point calculations. This problem is solved through the typeless feature of PHP. First, strval is converted into a string, and then the type is automatically recognized. The strval() function has been used to calculate the percentage below
Calculate the percentage
$successRate = floor(strval((2/3)*10000))/10000*100; $result = $successRate.'%';
2. Rounding situation
round function
float round ( float val [, int precision])
Returns the result of rounding val according to the specified precision (the number of digits after the decimal point).
precision can also be negative or zero (default).
<?php echo round(3.4); // 3 echo round(3.5); // 4 echo round(3.6); // 4 echo round(3.6, 0); // 4 echo round(1.95583, 2); // 1.96 echo round(1241757, -3); // 1242000 echo round(5.045, 2); // 5.04 echo round(5.055, 2); // 5.06
sprintf function
implements rounding, and if it does not have decimal places, it will automatically fill the specified decimal place with the specified character (specified 0) Number of digits
echo sprintf("%01.2f", 5.228); // 5.23 echo sprintf("%01.2f", 5.224); // 5.22 echo sprintf("%01.2f", 5); // 5.00
number_format function
If it does not have a decimal place, it will automatically fill it with 0 to the specified number of decimal places
echo number_format(5.228,2); // 5.23 echo number_format(5.224,2); // 5.22 echo number_format(5,2); // 5.00
round function
This function can achieve rounding, but if it does not have decimal places, it will not have decimal places after processing
echo round(5.228,2); // 5.23 echo round(5.224,2); // 5.22 echo round(5,2); // 5
php further Rounding method
echo ceil(4.4); // 5 echo ceil(4.6); // 5
PHP rounding method
echo floor(4.4); // 4 echo floor(4.6); // 4
Recommended related tutorials: "PHP Tutorial"
The above is the detailed content of Introduction to several methods of retaining two decimal places in PHP. For more information, please follow other related articles on the PHP Chinese website!