0

I have a small issue with BIG numbers where BC Maths function bcdiv is always returning zero on non-zero results.

For example :

echo bcdiv(40075036, 86164.098903691, 40);

Versus the traditional method :

echo (40075036/86164.098903691);

I am not sure why the discrepency. Do BC Math functions only work on strings, and if so, how can i convert int values into strings before hand (inline notation preferred such as (int)$myvar; ) --- if that is the problem.

Kraang Prime
  • 9,981
  • 10
  • 58
  • 124
  • 2
    It works as expected: http://3v4l.org/oZnah – sectus Apr 14 '14 at 01:00
  • I get `465.1013184132923257871676996731125104414750`. Seems to work just fine. – Sverri M. Olsen Apr 14 '14 at 01:43
  • @SverriM.Olsen - for the bcdiv operation, I am getting 0. I did change it in my local test while waiting for an answer to `bcdiv('40075036', '86164.098903691', '40');` which produces the expected result. One would figure PHP would be smarty enough to automatically convert the passed values to strings :S – Kraang Prime Apr 14 '14 at 01:45
  • Er... You've misunderstood how arbitrary precision libraries work. You're expected to handle numbers as **strings**. With numbers, you'll often get unexpected (or plain wrong) results. – Álvaro González Apr 14 '14 at 15:13

2 Answers2

1

The solution to this problem was as follows:

bcmath operations only work with strings. You can not pass any other type of data as the parameters as it will not do any calculations unless the values are (string).

The set of functions will not automatically convert or cast the data into string, and NO ERROR WILL BE RETURNED if passing other data types.

To pass the data that is stored in an integer, float, etc, the following code will work for dynamic conversion of the variable data as needed:

bcdiv((string)40075036, (string)86164.098903691, (string)40);

OR

$num1 = 12345;
$num2 = 45678;
$digits = 40;

bcdiv((string)$num1, (string)$num2, (string)$digits);

If the numbers are fixed and known BEFORE you pass (aka, they aren't coming from a database, and aren't pre-calculated), then you should use the function as follows :

bcdiv('40075036', '86164.098903691', '40');
Kraang Prime
  • 9,981
  • 10
  • 58
  • 124
  • I'm facing a very strange case where even casting to string wont work: `bcmul((string) $item['quantity'], (string) $item['price'], (string) $this->decimals);`. This fails when number has 4 digits. Otherwise it works. – mayid May 23 '18 at 17:09
  • Reason was I was previously formatting the numbers with `number_format` and that was adding a comma (although I couldn't actually see it when debugging) – mayid May 23 '18 at 17:15
1

Use the "bcscale" function - Set default scale parameter for all bc math functions. Ex.:

bcscale(40);
echo bcdiv(40075036, 86164.098903691);

It worked for me. (php 7.1)

bcscale manual