商品价格格式化

  /*
     * number_price(准备要开始的价格,要保留的小数位数,小数点显示的符号,千分位分隔符)
     * php4,php5
     * 默认将进行四舍五入处理
    */

    //牛刀小试,深入其意
    $old_price = '123456.345';
    $new_price01 = number_format($old_price,2,'.',',');
    var_dump($new_price01);//123,456.35
    $new_price02 = number_format($old_price,2,'.','');
    var_dump($new_price02);//123456.35
   
    $old_price02 = '123456.344';
    $new_price03 = number_format($old_price02,2,'.','');
    var_dump($new_price03);//123456.34

    //直接舍弃,不采用四舍五入取之
    $new_price04 = substr(number_format($old_price,3,'.',''),0,-1);
    var_dump($new_price04);//123456.34

    //直接取整
    $old_price03 = '666.66';
    $new_price05 = intval($old_price03);
    var_dump($new_price05);//666

    //四舍五入后去整
    $new_price06 = number_format($old_price03,0,'','');
    var_dump($new_price06);//667
/**
* 格式化商品价格
*
* @access public
* @param float $price 商品价格
* @return string
*/
function price_format($price, $change_price = true){
    if($price==='')
    {
     $price=0;
    }
    if ($change_price)
    {
        switch ($change_price)
        {
            case 0:
                $price = number_format($price, 2, '.', '');
                break;
            case 1: // 保留不为 0 的尾数
                $price = preg_replace('/(.*)(\\.)([0-9]*?)0+$/', '\1\2\3', number_format($price, 2, '.', ''));

                if (substr($price, -1) == '.')
                {
                    $price = substr($price, 0, -1);
                }
                break;
            case 2: // 不四舍五入,保留1位
                $price = substr(number_format($price, 2, '.', ''), 0, -1);
                break;
            case 3: // 直接取整
                $price = intval($price);
                break;
            case 4: // 四舍五入,保留 1 位
                $price = number_format($price, 1, '.', '');
                break;
            case 5: // 先四舍五入,不保留小数
                // $price = round($price);
                //取两位小数,
                $price = number_format($price, 2, '.', '');
                break;
        }
    }  
    else
    {
        $price = number_format($price, 2, '.', '');
    }
    //return sprintf($GLOBALS['_CFG']['currency_format'], $price);
    return $price;
}

 

posted on 2016-11-26 15:23  爱吃柠檬不加糖  阅读(769)  评论(0编辑  收藏  举报

导航