See the topic believe that a lot of small partners will think of using rounding method to achieve, this is also a way, then there are other methods, we will take you to understand the PHP implementation of two decimal places to save several ways!
PHP takes two digits after the decimal point.
Method One, often used after the decimal point to take a few, but can not carry the situation.
For example, 3.149569 takes two digits after the decimal point, and the last two bits cannot be rounded. Results: 3.14.
You can use the function floor.
The function is to take the rounding off. For example, floor (4.66456) results: 4.
Floor (9.1254) Results 9.
Therefore, to two digits after the decimal point, you need to multiply by 100, then take the whole, then divide by 100, namely:
$a =floor (3.149569*100)/100
Calculate percentage:
code example:
$successRate = Floor ((2/3 ') *10000)/10000*100; $result = $successRate. ' %';
Output Result:
66.67%
Method two, round function
Description
Float round (float val [, int precision])
Returns the result of rounding Val based on the specified precision precision (number of digits after decimal point).
Precision can also be negative or 0 (the default value).
Example:
code example:
<?phpecho round (3.4); 3echo round (3.5); 4echo round (3.6); 4echo Round (3.6, 0); 4echo round (1.95583, 2); 1.96echo round (1241757,-3); 1242000echo round (5.045, 2); 5.04echo round (5.055, 2); 5.06?>
Attention:
The round () is in an odd number of times, rounding the exact half of the score.
If you want to force it on. 5 (or. 05), always round in one direction, plus or minus a very small factor.
The reason behind the value of half of the value of the other half is to avoid the traditional banking problem, that is, if the bank always takes more money from its customers, it will eventually lose money if it always goes into a bank.
The average rounding for this is statistically balanced.
Three, sprintf function
The last one is to use the sprintf function, please refer to the article: Introduction to the usage analysis of the sprintf () function in PHP.
Summarize:
This article introduces three ways to implement PHP to retain two decimal places, each method has its different, can according to their own needs to choose a suitable one!
Related recommendations:
PHP retains two decimal places and rounding and non-rounding methods
How PHP retains two decimal places with the tail-off method
JS and PHP reserved Two-bit decimal example rounding using function tofixed ()