PHP round to exact decimal place and round
- 2020-12-13 18:51:50
- OfStack
Integer 1 method into the whole, 4 round 5 into the whole, ignore decimals, etc
PHP takes the four common methods of integer function, the following four functions are collected; We often use the integral function, today's little summary 1 next! ceil, floor, round, intval. ceil, floor, round, intval
PHP takes the four common methods of integer function, the following four functions are collected;
We often use the integral function, today's little summary 1 next! ceil, floor, round, intval
1. ceil -- Round off the 1 method
instructions
float ceil ( float value )
Returns the next integer not less than value, carrying 1 digit if value has a decimal part. The type returned by ceil() is still float, because the range of float values is usually larger than integer.
Example 1. ceil()
<?php
echo ceil(4.3); // 5
echo ceil(9.999); // 10
?>
2. floor -- Round off by discarding
instructions
float floor ( float value )
Returns the next integer not greater than value, rounding off the decimal portion of value. The type returned by floor() is still float, because the range of float values is generally larger than integer.
Example 1. Examples of floor()
<?php
echo floor(4.3); // 4
echo floor(9.999); // 9
?>
3. round -- Rounds 4 to 5 floating point numbers
instructions
float round ( float val [, int precision] )
Returns val rounded to 5 with the specified precision precision, the number of digits after the decimal point. precision can also be negative or zero (default).
Example 1. round()
<?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.05
echo round(5.055, 2); // 5.06
?>
4. intval - Converts variables to integer type
Example intval ()
<?php
echo intval(4.3); //4
echo intval(4.6); // 4
?>
PHP4 rounds 5 into exact decimal places and rounding
(1)php retains 3 decimal places and rounds 4 into 5
$num=0.0215489;
echo sprintf("%.3f", $num); // 0.022
(2)php retains 3 decimal places without rounding 4 into 5
$num=0.0215489;
echo substr(sprintf("%.4f", $num),0,-1); // 0.021
(3)php integer 1 method (this is used in the paging program page)
echo ceil(4.3); // 5
echo ceil(9.999); // 10
(4)php truncated method to take integer
echo floor(4.3); // 4
echo floor(9.999); // 9
(5), round function
Example 1. round()
<?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.05
echo round(5.055, 2); // 5.06
?>
PHP4 rounding into 5 is the most accurate way to keep two decimal places
<?php
$number = 123213.066666;
echo sprintf("%.2f", $number);
?>
Output results:
123213.07