【问题标题】:How to convert 0.5 to 0.50 in php [duplicate]如何在php中将0.5转换为0.50 [重复]
【发布时间】:2017-09-11 12:53:32
【问题描述】:

是否有可能在php中将“0.5”显示为“0.50”?

我不是那个意思:

<?php
    $x = 0.5;
    echo($x . "0");
?>

所以这也适合:

$x = 0.75;

我希望我的问题足够准确。 感谢您的帮助!

【问题讨论】:

    标签: php


    【解决方案1】:

    做:

    $x = 0.5;
    printf("%.2f", $x);
    

    获取:

    0.50
    

    说明:

    printf()sprintf() 可以打印/返回格式化字符串。有很多format parameters 可用。在这里,我使用了%.2f。让我们把它分开:

    • % 表示将替换为 $x 的占位符
    • . 表示 精度说明符
    • 2 属于精度说明符 - 小数点后的位数
    • f类型说明符,这里是 float,因为这就是我们要传入的内容

    或者:

    使用number_format()

    echo number_format($x, 2);
    

    这里,2 表示您希望输出中的小数位数。您实际上不需要提供第三个和第四个参数,因为它们的默认值正是您想要的。

    【讨论】:

      【解决方案2】:

      使用 number_format() 函数

      echo number_format($x,  2, '.', '');
      

      【讨论】:

      • 好的已修复,未测试
      【解决方案3】:

      使用number_format函数

      <?php
      print number_format('0.5',2,'.','');
      
      // 0.50
      ?>
      

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

      【讨论】:

        【解决方案4】:

        你需要使用 number_format

         $x = 0.5;
         echo number_format($x, 2, '.', '');
        

        输出 = 0.50

        【讨论】:

          【解决方案5】:

          我认为使用.. sprintf("%.02f",$string); 或 number_format()

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-06-10
            • 2015-02-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-06-06
            • 2011-06-06
            • 2023-03-23
            相关资源
            最近更新 更多