【问题标题】:how to remove the last two zero?如何删除最后两个零?
【发布时间】:2011-09-23 14:05:12
【问题描述】:

我有一个名为zen_get_products_discount_price_qty($new_products->fields['products_id']) 的函数,它会输出:$8.0000。 我想把$8.0000 变成$8.00。我该怎么做?

【问题讨论】:

    标签: php zen-cart


    【解决方案1】:

    使用number_format函数

    【讨论】:

      【解决方案2】:
         $output = zen_get_products_discount_price_qty($new_products->fields['products_id']);
         $output =  substr($output,0,-2);
      

      【讨论】:

      • 函数 substr() 不是最好的解决方案。它没有四舍五入!
      • @Scoutman 值以 '$' 为前缀,因此它不会将其用于数学运算,可能只是想将其呼应出来,因此 substr 适合此处。
      【解决方案3】:

      试试这个:

      $value = '$8.0000';
      $value = str_replace('$', '', $value);
      $value = number_format($value, 2);
      echo $value;
      

      http://at2.php.net/number_format

      使用 number_format 获取正确的值很重要。函数 substr() 只删除最后两个零。函数 number_format() 对数字进行四舍五入。

      number_format(8.1199, 2); // == 8.12 - correct
      substr(8.1199, 0, -2); // == 8.11 - false!
      

      【讨论】:

        【解决方案4】:

        先删除 $ 然后使用 round() 函数。

        【讨论】:

          【解决方案5】:
          printf('$%.02f', 8.0000); // $8.00
          

          【讨论】:

            【解决方案6】:

            或者 preg_replace :)

            echo preg_replace("/^\$(\d+?)(?:.\d*)?$/", "\$$1.00", '$8.0000');

            产出:$8.00

            【讨论】:

              【解决方案7】:

              不要使用任何 substr()、printf()、number_format() 等解决方案。他们不处理可能有不同显示要求的美元以外的货币。改用 Zen Cart 全局 $currencies 对象:

              $currencies->format($my_price);
              

              检查 includes/classes/currencies.php 以供参考。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2021-12-24
                • 2017-03-17
                • 1970-01-01
                • 2017-08-02
                • 2014-08-19
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多