Home  >  Article  >  Backend Development  >  How does the sprintf() function in php implement price formatting?

How does the sprintf() function in php implement price formatting?

不言
不言Original
2018-08-23 10:43:192352browse

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(&#39;Content-Type:text/html;Charset=utf-8&#39;);
 $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(&#39;.&#39;, $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

PHP's sprintf function usage detailed explanation, sprintf function detailed explanation_PHP tutorial

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn