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;
    }
  • 相关阅读:
    03、CPU主频,和性能
    02、计算机组成原理相关知识
    常用正则表达式,手机号、固话号、身份证号等
    01、计算机原理结构,及冯诺依曼体系结构
    7-7 Complete Binary Search Tree (30分) 完全二叉搜索树
    7-2 Reversing Linked List (25分)
    7-1 Maximum Subsequence Sum (25分)
    6-17 Shortest Path [4] (25分)
    6-16 Shortest Path [3] (25分)
    6-15 Iterative Mergesort (25分)
  • 原文地址:https://www.cnblogs.com/wanghaokun/p/6104299.html
Copyright © 2011-2022 走看看