混淆了PHP的bcmul()比例

时间:2011-06-21 16:27:26

标签: php bcmath

为什么输出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

?>

4 个答案:

答案 0 :(得分:4)

这是87.50的四舍五入,因为87.5将是相同的。要修复,你需要:

number_format("87.50",2);

答案 1 :(得分:2)

使用number_format()代替bcmul()

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

对于php <7.3使用

$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