Content of this section:
How to round decimals in php and js
The first part:
1, discard the decimal part and keep the integer part
Copy codeCode example:
php: intval(7/2) js:parseInt(7/2)
2, round up, if there is a decimal, add 1 to the integer part
Copy codeCode example:
php: ceil(7/2) js: Math.ceil(7/2)
3, round down.
Copy codeCode example:
php: round(7/2) js: Math.round(7/2)
4, round down
Copy codeCode example:
php: floor(7/2) js: Math.floor(7/2)
Part 2, PHP roundingCommonly used functions
In phpProgramming, the commonly used rounding functions are ceil, floor, round, intval .
Let’s introduce them separately.
1, ceil -- rounding method
Introduction
float ceil (float value)
Return not less than =noted id =note_temp>value is the next integer. If value has a decimal part, it will be carried. The return type of ceil() is still float. The float value range is usually larger than eger.
Example 1. ceil
Copy code code example:
<?php echo ceil(4.3); // 5 echo ceil(9.999); // 10 ?>
2, floor -- rounding by rounding off method
Introduction
float floor ( float value )
Return the next integer not greater than value will be value as a decimal Partial rounding and rounding floor return type is still float float value range is usually larger than eger
Example 1. floor
Copy code code example:
<?php echo floor(4.3); // 4 echo floor(9.999); // 9 ?>
3, round -- round floating point numbers by 4 and 5
Introduction
float round (float val [, precision])
Return val according to Specify precision (the number of digits after the decimal point) to round the result precision. It can also be a negative number or zero (default value)
Example 1. round
Copy code code example :
<?php echo round(3.4); // 3 echo round(3.5); // 4 echo round(3.6);// 4 echo round(3.6, 0);// 4 // www.jbxue.com 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, val---convert the variable into an integer type
Example 1, val
Copy code code example:
<?phpecho val(4.3); //4echo val(4.6); // 4 ?>
The above is the detailed content of PHP decimal rounding example tutorial. For more information, please follow other related articles on the PHP Chinese website!