php 进一法格式化浮点数为特定位数 可用于格式化价格

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

我们经常用到进一法需要保留几位小数。这里提供一个函数。

// $price为要格式化的数,$number为需要格式化的位数 使用此函数需要安装 BCMath 扩展
function format_price($price,$number=2){
    $format_price = bcadd($price,0,$number);
    $num = strripos($price,".");
    if($num !==false){
        $precision = substr($price,$num+1+$number);
        if($precision > 0){
            $format_price  = bcadd($format_price,bcdiv(1,pow(10,$number),$number),$number);
        }
    }
    return $format_price;
}

猜你喜欢

转载自blog.csdn.net/u010454239/article/details/83858714