PHP bcmul() not using correct precision

58 Views Asked by At

I'm trying to use the PHP bcmath library to handle the problem of rounding errors in PHP.

My code:

$usdPerCoin = 2755905;
$amountToConvert = 1000;

function toFixed(string $number, int $precision = 8): string
{
    $number = bcmul($number, (string) pow(10, $precision));
    return bcdiv($number, (string) pow(10, $precision), $precision);
}

die(var_dump(bcmul(toFixed($amountToConvert / $usdPerCoin, 8), (string) 1e8)));

Using this code with the following values produces different output I cannot comprehend.

$anountToConvert = 1000; // produces string(5) "36285"
$anountToConvert = 2000; // produces string(5) "72571"

When using 2000 as value for $amountToConvert, the amount of the previous conversion should be doubled, but as you can see it's not doubled.

I expect the values to be:

$anountToConvert = 1000; // produces string(5) "36285"
$anountToConvert = 2000; // produces string(5) "72570"

I think it's caused because it's using internal not only a precision of 8. Any ideas how to prevent this?

0

There are 0 best solutions below