2

I'm trying to calculate a tax or discount value using BCMATH in PHP. I need 2 DECIMAL PLACES. Here's how i'm doing it:

bcscale(2);
$price = '60.67';
$discount = bcmul(bcdiv($price, 100), '3.8'); // calculate 3.8 percent from 60.67
// result is: 2.28
// result should be: 2.31

I could simply increase the scale to 4 or something like that and that would now give me a correct result.

So the question is: how should i do this correctly? Should i set the scale to 4 and then sprintf('%0.2f', $discount) in the end? Or is there a better way of doing this?

Marius
  • 3,976
  • 5
  • 37
  • 52

1 Answers1

2

Bypass bcmath?

$discount = round( ($price / 100) * 3.8, 2);
// 2.31
scrowler
  • 24,273
  • 9
  • 60
  • 92
  • Otherwise, try removing the quotes around 3.8 and put scale as third param: – scrowler Oct 02 '13 at 06:08
  • 2
    $discount = bcmul(bcdiv($price, 100), 3.8, 2); – scrowler Oct 02 '13 at 06:09
  • So you're saying i can bypass bcmath alltogether. Then ... what is the point of using it anyway and what are the situations in which i can bypass it? – Marius Oct 02 '13 at 06:37
  • Just saying if it's giving you incorrect results and your syntax is correct, just use regular PHP functions. You can use them inside your other code – scrowler Oct 02 '13 at 07:30
  • It would give correct results, using correct scale. And it's obvious why it doesn't in the first place. Just wondering if using a simple float math would not end up screwing something up even if it's a single operation ... – Marius Oct 02 '13 at 08:06
  • Shouldn't do, at the end of the day bc takes and returns integers so it shouldn't matter. For consistency you should stick with one or the other if you can though – scrowler Oct 02 '13 at 08:18
  • I believe I found the problem. BCMath doesn't round to the decimal place. Instead it simply cuts off at the decimal. Example: 2.325 in bcmath would be 2.32 not 2.33 – Hackmodford Dec 17 '13 at 15:00