How to keep 2 decimal places without rounding in php:
Keep 2 decimal places without rounding,
In fact we After understanding the characteristics of sprintf, we will keep one more decimal place after rounding, and then use substr to intercept the first two digits: the code is as follows
$n=0.1265489; echo sprintf("%.2f",substr(sprintf("%.3f", $n), 0, -1));//0.12
PHP keeps two decimal places and rounds, and uses the sprintf function to perform $n Formatted %.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;
$n=0.1265489; echo sprintf("%.2f", $n); // 0.13
round function
<?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 ?>
Recommended tutorial: "php tutorial"
The above is the detailed content of How to keep 2 decimal places without rounding in php. For more information, please follow other related articles on the PHP Chinese website!