Search code examples
phpbcmath

confused by PHP's bcmul() scale


Why is this outputting 87.5 and not 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

?>

Solution

  • Use number_format() instead of bcmul()

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