1

我试图在 PHP 中乘以一些小数字,但 bcmul 返回零,因为浮点值正在变成科学记数法。

我尝试sprintf('%.32f',$value)在小的浮点值上使用,但由于小数位数未知,因此舍入错误,然后乘法时会导致舍入错误。

另外,我不能用strpos('e',$value)它来找出它是否是科学记数法数字,因为即使我将它转换为字符串也找不到它(string)$value

这是一些示例代码:

  $value = (float)'7.4e-5'; // This number comes from an API like this

  $value2 = (float)3.65; // Another number from API

  echo bcmul($value,$value2); // 0
4

2 回答 2

1

默认情况下,bc 函数四舍五入为 0 位小数。您可以通过使用bcscale或通过更改bcmath.scalephp.ini 中的值来更改此行为。

于 2020-10-31T10:14:51.403 回答
0

好的,我找到了解决它的方法,所以,这里是如何将非常小的浮点数相乘,而无需为数字设置显式比例:

function getDecimalPlaces($value) {
// first we get how many decimal places the small number has
// this code was gotten on another StackOverflow answer

   $current = $value - floor($value);
   for ($decimals = 0; ceil($current); $decimals++) {
      $current = ($value * pow(10, $decimals + 1)) - floor($value * pow(10, $decimals + 1));
   }
   return $decimals;
} 

function multiplySmallNumbers($value, $smallvalue) {
    
   $decimals = getDecimalPlaces($smallvalue); // Then we get number of decimals on it
   $smallvalue = sprintf('%.'.$decimals.'f',$smallvalue ); // Since bcmul uses the float values as strings, we get the number as a string with the correct number of zeroes
   return (bcmul($value,$smallvalue));
}
于 2020-11-06T04:42:19.373 回答