【问题标题】:How do I format numbers to have only two decimal places?如何将数字格式化为只有两位小数?
【发布时间】:2010-01-02 18:43:15
【问题描述】:

我希望实数例如是 12.92,而不是 12.9241。这样可以吗?

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    在 PHP 中,尝试 number_format:

    $n = 1234.5678;
    
    // Two decimal places, using '.' for the decimal separator
    // and ',' for the thousands separator.
    $formatted = number_format($n, 2, '.', ',');
    // 1,234.57
    

    【讨论】:

      【解决方案2】:

      对于 PHP,您可以使用 number_format(),对于 MySQL,使用 FORMAT() 函数。

      MySQL:http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_format

      FORMAT(number, 2)
      

      例子:

      mysql> SELECT FORMAT(12332.123456, 4);
             -> '12,332.1235
      

      PHP:http://php.net/manual/en/function.number-format.php

      $number = 1234.5678;
      $formatted_number = number_format($number, 2, '.', '');
      // 1234.56
      

      【讨论】:

      • 如果你不想要千位分隔符,你也可以用同样的方式使用 ROUND()。
      【解决方案3】:
      $number = 1234.5678;
      $teX = explode('.', $number);
      
      if(isset($teX[1])){
          $de = substr($teX[1], 0, 2);
          $final = $teX[0].'.'.$de;
          $final = (float) $final;
      }else{
          $final = $number;   
      }
      

      最终将是 1234.56

      【讨论】:

        【解决方案4】:

        您可以将数字乘以 100,对结果进行四舍五入,然后再除以 100。

        或者在php中使用round函数round function

        $result=round(12.9241, 2);
        

        【讨论】:

          猜你喜欢
          • 2023-03-03
          • 2011-06-04
          • 1970-01-01
          • 2015-05-20
          • 1970-01-01
          • 1970-01-01
          • 2020-10-12
          • 2021-09-03
          • 2011-01-10
          相关资源
          最近更新 更多