Home > Article > Backend Development > How does the sprintf() function in php implement price formatting?
The content of this article is about how the sprintf() function in PHP implements price formatting. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Summary: In different business scenarios, the implementation logic is also different. Generally, use method 2
Method 1
<?php/** * User: Jack * Date: 2017/11/27 * Time: 19:43 */ header('Content-Type:text/html;Charset=utf-8'); $a = 155.8888; if (getFloatLength($a) > 2) { echo formatNum($a,2); } //格式化function formatNum($input, $num){ return sprintf("%." . $num . "f", $input); } //计算小数点后面的位数function getFloatLength($num){ $count = 0; $temp = explode('.', $num); if (sizeof($temp) > 1) { $decimal = end($temp); $count = strlen($decimal); } return $count; }
Method 2
function formatItemPrice($price, $num = 2){ $str = sprintf("%." . $num . "f", $price); return strval(floatval($str)); }
Related recommendations:
Detailed explanation of sprintf function usage in PHP, detailed explanation of sprintf function
The above is the detailed content of How does the sprintf() function in php implement price formatting?. For more information, please follow other related articles on the PHP Chinese website!