流苏小筑

PHP自定义函数(1)--- 格式化金钱

对数字进行格式化,以类似¥10,000,000的格式

/**
 * @name   小数位截取格式化金额  例如 100000.00 -> 100,000.00
 * @param  float    $num  [格式化前的金额]
 * @param  integer  $dist [保留的小数位数]
 * @param  BOOL     $zeroComplete [小数位不够dist时,是否用0补齐] 
 * @return [type]         [description]
 */

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;
}

输出样式

¥1,231,243.00

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »