Home >Backend Development >PHP Tutorial >PHP rounding, rounding, round function usage examples, rounding round_PHP tutorial
Decimal example:
PHP keeps two decimal places and rounds
You can see that we used the sprintf function to format $n%. 2f is the target format, where 2 represents two digits and f represents float (floating point type). The third is a decimal 6 that is rounded
Let’s look at another example
The code output retains 2 as a decimal without rounding. In fact, we understand that the characteristics of sprintf will round the decimal and we retain one more digit, and then use substr to intercept the first 2 digits
Rounding example:
The ceil function is an upward rounding function. What does upward mean? That is to say, if it exceeds a little bit, move forward one bit. For example, 4.1 becomes 5 in the example.
On the contrary, there is a function called floor. Let’s take a look at its usage
The characteristics of floor are particularly obvious in the second output, that is, without giving you how many decimal places, even if it is infinitely close to 10, the integer you get by going down is 9.
round function
The description of the round function in the PHP manual is:
float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )
Returns val rounded to the specified precision (the number of decimal digits after the decimal point). precision can also be negative or zero (default).
round is the data source, the second parameter is the number of decimal places to be retained and the next one (for example, if you enter 2, then the third one is the last one) is rounded. When it is a negative number, from Count the corresponding length from the last digit of the data source to 0 and round the last digit. For example, round(123456,-2) is 123456, starting from 6 and counting both digits to zero, and the last digit is 5 (from The first digit from the back to the front is 6 and the last digit is 5) is rounded, and the output is 123500