3

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

?>
Dave Kiss
  • 10,289
  • 11
  • 53
  • 75
  • Because the second decimal is a zero...it's no more preceise than 87.5. If you specified 3, and the result was 87.501, then the zero would be included. – AJ. Jun 21 '11 at 16:30
  • I was under the impression the scale displays whichever number you throw at it. Should I use `number_format()` to show it? – Dave Kiss Jun 21 '11 at 16:32

4 Answers4

4

It is rounding the 87.50 as 87.5 would be the same. To fix, you'd need:

number_format("87.50",2);
Francis Gilbert
  • 3,382
  • 2
  • 22
  • 27
2

Use number_format() instead of bcmul()

echo number_format(bcmul($price, $quantity, 2), 2, '.'); // forces to output always 2 diget after .
powtac
  • 40,542
  • 28
  • 115
  • 170
2

Mathmatically 87.5 is 87.50. If you need additional number padding, you can use number_format or money_format to display the extra 0

datasage
  • 19,153
  • 2
  • 48
  • 54
0

for php < 7.3 use

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

// $val = "10.00"

or use php >= 7.3 it fixed

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

Naskalin
  • 895
  • 9
  • 9