为什么 Bcmath 返回不准确的结果
Why is Bcmath returning innacurate results
我无法让 bcmath 在我的服务器上处理基于比特币的分数 php 7.1,ubuntu 18。查看以下代码
bcscale(8);
$x1 = bcsub(0.04217 ,0.00007, 8);
$x2 = 0.04217 - 0.00007 ;
dd($x1 , $x2);
结果
"0.04217000"
0.0421
如您所见,bcmath 得到 return 第一个操作数,其中添加了一些零??。
有什么想法吗?
手册有点微妙,但是参数应该是字符串。如果你把它们变成字符串,它就会起作用。
bcscale(8);
$x1 = bcsub('0.04217' ,'0.00007', 8);
$x2 = 0.04217 - 0.00007 ;
echo 'x1 = '. $x1 . PHP_EOL;
echo 'x2 = '. $x2;
结果
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).
关于精度,
bcscale(8);
$x1 = bcsub('0.04217' ,'0.00007', 6);
// ^
$x2 = 0.04217 - 0.00007 ;
echo 'x1 = '. $x1 . PHP_EOL;
echo 'x2 = '. $x2;
结果
x1 = 0.042100
x2 = 0.0421
和
bcscale(8);
$x1 = bcsub('0.04217' ,'0.00007', 4);
// ^
$x2 = 0.04217 - 0.00007 ;
echo 'x1 = '. $x1 . PHP_EOL;
echo 'x2 = '. $x2;
结果
x1 = 0.0421
x2 = 0.0421
我无法让 bcmath 在我的服务器上处理基于比特币的分数 php 7.1,ubuntu 18。查看以下代码
bcscale(8);
$x1 = bcsub(0.04217 ,0.00007, 8);
$x2 = 0.04217 - 0.00007 ;
dd($x1 , $x2);
结果
"0.04217000"
0.0421
如您所见,bcmath 得到 return 第一个操作数,其中添加了一些零??。 有什么想法吗?
手册有点微妙,但是参数应该是字符串。如果你把它们变成字符串,它就会起作用。
bcscale(8);
$x1 = bcsub('0.04217' ,'0.00007', 8);
$x2 = 0.04217 - 0.00007 ;
echo 'x1 = '. $x1 . PHP_EOL;
echo 'x2 = '. $x2;
结果
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).
关于精度,
bcscale(8);
$x1 = bcsub('0.04217' ,'0.00007', 6);
// ^
$x2 = 0.04217 - 0.00007 ;
echo 'x1 = '. $x1 . PHP_EOL;
echo 'x2 = '. $x2;
结果
x1 = 0.042100
x2 = 0.0421
和
bcscale(8);
$x1 = bcsub('0.04217' ,'0.00007', 4);
// ^
$x2 = 0.04217 - 0.00007 ;
echo 'x1 = '. $x1 . PHP_EOL;
echo 'x2 = '. $x2;
结果
x1 = 0.0421
x2 = 0.0421