【问题标题】:Always display specified number of decimal places in PHP (rounding up)始终在 PHP 中显示指定的小数位数(向上舍入)
【发布时间】:2012-10-20 14:45:50
【问题描述】:

我需要显示一个具有指定小数位数(向上舍入)的浮点数,特别是最多两位小数,即使该数字没有小数部分。我知道的一种方法是使用sprintf() PHP 函数,如下所示。

echo sprintf("%0.2f", 123);

它返回123.00

echo sprintf("%0.2f", 123.4555);

返回123.46,但以下内容没有返回我需要的内容。

echo sprintf("%0.2f", 123.455);  // 5 is removed - the right-most digit.

我希望它返回123.46,但它没有。它返回123.45。虽然差别不大,但在这两种情况下我都需要返回123.46


round() 函数可以做到这一点。 echo round(123.455, 2);echo round(123.4555, 2); 在这两种情况下都返回 123.46 但我想不出使用这个函数,因为如果小数部分不存在,它根本不显示小数位。比如echo round(123, 2);123,我需要123.00

PHP 中是否有实现此功能的函数?

【问题讨论】:

    标签: php rounding


    【解决方案1】:
    number_format(123.455, 2, '.', '')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 2014-05-03
      • 1970-01-01
      • 2016-06-01
      相关资源
      最近更新 更多