Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why subtraction doesn't work properly using bcmath?

Tags:

php

math

bcmath

Let's say I have

$foo = bcsub(bcdiv(1, 3, 20), 0.00001, 20);

it returns me 0.33333333333333333333

If I have

$foo = bcsub(bcdiv(1, 3, 20), 0.0001, 20);

it returns me 0.33323333333333333332

If I have

$foo = bcsub(0.333333333333333333, 0.00001, 20);

it returns me 0.33333333333333331483

If I have

$foo = bcsub(0.333333333333333333, 0.0001, 20);

it returns me 0.33323333333333331482

So why it can't properly subtract, it's something with floating point? But it works fine when just bcdiv(1, 3, 20)

like image 665
Templar Avatar asked Jan 20 '26 19:01

Templar


1 Answers

Use strings instead of floats as parameters to the BC functions:

$foo = bcsub(bcdiv("1", "3", "20"), "0.00001", "20");

If you use a float (i.e. 0.00001), PHP will convert this number to a float, which is not precise. If you use a string (i.e. "0.00001"), BC will do the conversion to an arbitrary precision number, which is precise.

like image 132
Sjoerd Avatar answered Jan 23 '26 08:01

Sjoerd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!