When we need to keep the output data to two decimal places, what should we do? Today I will introduce to you how to format a number with two decimal places in PHP. You can refer to it if you need it.
Due to business needs, a number needs to be formatted to two decimal places (rounded):
Code:
$aaa = 15.0393; var_dump(round($aaa, 2)); $bbb = 16.1; var_dump(round($bbb, 2)); $ccc = 13; var_dump(round($ccc, 2)); /** 运行: double(15.04) double(16.1) double(13) */
There is a problem with this solution. If the original number has only one decimal or no decimal, it will be output as usual without adding 0 at the end. If rounding up or down, use ceil or floor.
Code:
$aaa = 15.0393; var_dump(number_format($aaa, 2, '.', '')); $bbb = 16.1; var_dump(number_format($bbb, 2, '.', '')); $ccc = 13; var_dump(number_format($ccc, 2, '.', '')); /** 运行: string(5) "15.04" string(5) "16.10" string(5) "13.00" */
Although this solution can be filled with 0 at the end, it will be converted into a string.
Code:
$aaa = 15.0393; var_dump(sprintf('%.2f', $aaa)); $bbb = 16.1; var_dump(sprintf('%.2f', $bbb)); $ccc = 13; var_dump(sprintf('%.2f', $ccc)); /** 运行: string(5) "15.04" string(5) "16.10" string(5) "13.00" */
is the same as above.
// ToDo: There is no good solution that can add 0 at the end and output a numeric type instead of a string.
Recommended learning: php video tutorial
The above is the detailed content of How to output numbers with two decimal places in PHP. For more information, please follow other related articles on the PHP Chinese website!