Valentine Morozov
Valentine Morozov

Reputation: 123

bcmath operations with very small numbers

I want to use bcmath for precise operations with very small numbers, but it fails. I am trying to calculate cryptocurrency prices and thought that bcmath is better than converting float to integers

This working:

php > echo number_format(0.000005 * 0.0025, 10);

0.0000000125

And this is not working:

php > echo number_format(bcmul(0.000005, 0.0025, 10), 10);

0.0000000000

php > echo number_format(bcadd(0.000005, 0.00000025, 10), 10);

0.0000000000

Is there some configurations for bcmath or this is normal behavior?

Upvotes: 1

Views: 288

Answers (1)

Alex Howansky
Alex Howansky

Reputation: 53573

You need to pass the bc* function arguments as strings. Otherwise, they're interpreted as native floats and subject to the limits thereof.

echo bcmul('0.000005', '0.0025', 10), "\n";
echo number_format(bcmul('0.000005', '0.0025', 10), 10), "\n";

Outputs:

0.0000000125
0.0000000125

Upvotes: 3

Related Questions