-1

Im having trouble getting bcmath to work with bitcoin based fractions on my server php 7.1 , ubuntu 18. Look at the following Code

bcscale(8);
$x1 = bcsub(0.04217 ,0.00007, 8);
$x2 = 0.04217 - 0.00007 ;
dd($x1 , $x2);

Result

"0.04217000"
0.0421

As you can see bcmath get return the first operand with some zeros added to it??. Any Ideas?

ofumbi
  • 334
  • 1
  • 4
  • 11
  • 2
    Is this not a clue? `bcscale(8);` or the `,8` in the `bcsub()` – RiggsFolly Feb 05 '19 at 11:25
  • @RiggsFolly Why? the subtraction was not done. it merely formats? – ofumbi Feb 05 '19 at 11:27
  • 2
    You're explicitly telling it to use 8 decimal points - twice! "*This optional [3rd] parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the bcscale() function, or fallback to 0 if this has not been set.*" as per the docs http://php.net/bc-sub – Qirel Feb 05 '19 at 11:30
  • @Qirel Yes Im aware, But the result is wrong. I expect 0.0421 as shown by simple php calculation or at least 0.04210000. why is the 7 still there? Just subtracted it – ofumbi Feb 05 '19 at 11:34
  • Possible duplicate of [bcmath operations with very small numbers](https://stackoverflow.com/questions/47100116/bcmath-operations-with-very-small-numbers) – Matt Raines Apr 15 '19 at 15:40

1 Answers1

3

The manual is a little subtile but, the parameters are supposed to be strings. If you make them strings it will work.

bcscale(8);
$x1 = bcsub('0.04217' ,'0.00007', 8);
$x2 = 0.04217 - 0.00007 ;

echo 'x1 = '. $x1 . PHP_EOL;
echo 'x2 = '. $x2;

RESULT

x1 = 0.04210000
x2 = 0.0421

Also from the manual

Caution Passing values of type float to a BCMath function which expects a string as operand may not have the desired effect due to the way PHP converts float values to string, namely that the string may be in exponential notation (what is not supported by BCMath), and that the decimal separator is locale dependend (while BCMath always expects a decimal point).

As to the precision,

bcscale(8);
$x1 = bcsub('0.04217' ,'0.00007', 6);
//                                ^
$x2 = 0.04217 - 0.00007 ;

echo 'x1 = '. $x1 . PHP_EOL;
echo 'x2 = '. $x2;

RESULT

x1 = 0.042100
x2 = 0.0421

And

bcscale(8);
$x1 = bcsub('0.04217' ,'0.00007', 4);
//                                ^
$x2 = 0.04217 - 0.00007 ;

echo 'x1 = '. $x1 . PHP_EOL;
echo 'x2 = '. $x2;

RESULT

x1 = 0.0421
x2 = 0.0421
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • Yeah you are absolutely right, lost alot of money already, simple change of table mysql table column from string to DECIMAL (16 , 8) broke my whole application , what catch! Thanks. – ofumbi Feb 05 '19 at 11:38