【问题标题】:confused by PHP's bcmul() scale对 PHP 的 bcmul() 规模感到困惑
【发布时间】:2011-09-19 16:50:02
【问题描述】:

为什么输出的是87.5而不是87.50

<?php

$quantity = 25;
switch ($quantity)
{
    case ($quantity <= 50):
        $price = 3.50;
        break;
    case ($quantity <= 100):
        $price = 3.00;
        break;
    default:
        break;

}
echo bcmul($price, $quantity, 2);
// 87.5

?>

【问题讨论】:

  • 因为小数点后第二位是零……它并不比 87.5 更精确。如果您指定 3,结果为 87.501,则将包括零。
  • 我的印象是天平会显示你扔给它的任何数字。我应该使用number_format() 来显示它吗?

标签: php bcmath


【解决方案1】:

使用number_format() 代替bcmul()

echo number_format(bcmul($price, $quantity, 2), 2, '.'); // forces to output always 2 diget after .

【讨论】:

  • 我最初有这个,但决定开始始终使用bcmath 函数。没有其他选择吗?
  • 使用 bcmul() 后可以使用 number_format()。 number_format() 用于输出格式。
  • 在看到@Francis Gilbert 的回复后,我把它放在一起。谢谢!
【解决方案2】:

在数学上 87.5 是 87.50。如果需要额外的数字填充,可以使用number_formatmoney_format 显示额外的0

【讨论】:

    【解决方案3】:

    将 87.50 四舍五入,因为 87.5 相同。要修复,您需要:

    number_format("87.50",2);
    

    【讨论】:

      【解决方案4】:

      供php

      $val = bcmul('2', '5', 2);
      $val = number_format($val, 2, '.', '');
      
      // $val = "10.00"
      

      或使用 php >= 7.3 修复

      https://www.php.net/manual/en/function.bcmul.php#refsect1-function.bcmul-notes

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-24
        • 2014-11-27
        • 2022-01-04
        • 2011-06-10
        • 1970-01-01
        相关资源
        最近更新 更多