php利用sprintf() 函数格式化商品价格

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013101178/article/details/81946525

总结:不同的业务场景下,实现逻辑也不同,一般情况下使用方法2
方法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;
}

方法2

function formatItemPrice($price, $num = 2)
{
    $str = sprintf("%." . $num . "f", $price);
    return strval(floatval($str));
}

猜你喜欢

转载自blog.csdn.net/u013101178/article/details/81946525
今日推荐