PHP格式化金额,小数位截取而非四舍五入,末尾控制是否0补齐

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

格式化金额,小数位截取而非四舍五入


<?php



/**
 * @name   小数位截取格式化金额  例如 100000.00 -> 100,000.00
 * @param  float    $num  [格式化前的金额]
 * @param  integer  $dist [保留的小数位数]
 * @param  BOOL     $zeroComplete [小数位不够dist时,是否用0补齐] 
 * @return [type]        [description]
 */
if (!function_exists('numberFormat')) {
    function numberFormat($num = 0, $dist =2, $zeroComplete = TRUE) {
        
        if (!preg_match('/^(-?\d+)(\.\d+)?$/', $num)) {
            return $num;
        }
        if ($dist > 4) {
            $dist = 4;
        }else if ($dist <= 0) {
            $dist = 0;
        }
        if (!is_bool($zeroComplete)) {
            $zeroComplete = TRUE;
        }
        $newNum = floor($num * pow(10, $dist)) / pow(10, $dist);
        if (!$zeroComplete) {
            //去掉小数末尾的0 
            $newNum = floatZeroCut($newNum);
            $pos = strpos(strval($newNum), '.');//获取小数点位置
            if (!$pos) {
                //如果没找到
                $dist = 0;
            }else {
                $dist = strlen(strval($newNum)) - $pos - 1;
            }
        }
        $result = number_format($newNum, $dist);
        return $result;
    }
}

/**
 * 自动去掉小数末尾的0
 * @param  float  $num [小数]
 * @return float       [返回去掉小数末尾0的小数]
 */
if (!function_exists('floatZeroCut')) {
    function floatZeroCut($num = 0.00) {
        if (!preg_match('/^(-?\d+)(\.\d+)?$/', $num)) {
            return '参数错误';
        }
        if ((int)($num) == $num) {
            return $num;
        }
        $strNum = strval($num);
        if (substr($num, -1) == '0'){
            $strNum = substr($strNum, 0, strlen($num) - 1);
            return floatZeroCut(floatval($strNum));
        }else {
            return floatval($strNum);
        }
    }
}









猜你喜欢

转载自blog.csdn.net/u010889390/article/details/52621215