Search code examples
phpbcmath

bcmath seems to give the wrong answer to my calculation


I am not sure what I am doing wrong but this calculation

bcscale(20);
echo bcmul(bcdiv('422218', '2388865'), '473');

echoes "83.59999999999999999670" but every other calculator gives me 83.6.

Is there a way to solve this or is it a flaw in bcmath?


Solution

  • The reason you see this result is because you first perform the division.

    The division gives you:

    422218/2388865
    0.17674418604651162790697674418604651163
    

    but you ask for 20 digits, so that becomes 0.1767441860465116279. In that light, bc gives you now the correct result:

    0.1767441860465116279*473
    83.5999999999999999967
    

    A "solution" in this case would be to first perform the multiplication (which gives you "just" 9 digits) and then the division:

    bcscale(20);
    echo bcdiv(bcmul('422218','473'),'2388865');
    83.60000000000000000000