zoukankan      html  css  js  c++  java
  • 商品价格格式化

      /*
         * 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+$/', '123', 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;
    }
  • 相关阅读:
    利用正則表達式排除特定字符串
    js面向对象编程:this究竟代表什么?
    js调用父级frame中的方法
    Cocos2d-x动画工具类
    BZOJ 2466 中山市选2009 树 高斯消元+暴力
    Android Intent Scheme URLs攻击
    XML基础(一)
    【Life】 Never Too Late, Just Do it Better!
    代理模式
    HDU--Elevator(水题)
  • 原文地址:https://www.cnblogs.com/wanghaokun/p/6104299.html
Copyright © 2011-2022 走看看