【问题标题】:PHP very small decimals result in errorPHP非常小的小数导致错误
【发布时间】:2014-03-20 22:21:55
【问题描述】:

PHP 在处理小数/浮点数时出错。取以下代码:

$spotPrices['entry'] = 1.6591;
$price['o'] = 1.65908;

$currentresult = $spotPrices['entry'] - $price['o'];

echo $currentresult;

我希望这会输出0.00002(答案)。但它却输出:-1.99999999999E-5

为什么要这样做,更重要的是,我怎样才能得到正确的结果?


我在论坛上进行了一些搜索,发现浮点数适合 PHP,但没有看到似乎可以回答我的问题的解决方案或变通方法。

【问题讨论】:

  • 你打错了,$spotPrice vs $spotPrices
  • 如果您需要浮点数的精度,您应该查看高精度库,例如 bcmath 或不使用浮点数(转换为整数,即 value * 10000 并在显示上更改)。 php.net/manual/en/ref.bc.php

标签: php floating-point decimal floating-accuracy


【解决方案1】:

我的计算器说结果应该是 0.00002

使用 number_format:

$currentresult = number_format($spotPrices['entry'] - $price['o'], 8);

【讨论】:

  • 使用 number_format 为我的应用程序工作,谢谢
【解决方案2】:

你得到的不是 0.00002,而是 1.9999999999909E-5,即 0.000019999999999909。这是由于浮点精度。精度取决于平台。你可以在这里阅读:http://www.php.net/manual/en/language.types.float.php

【讨论】:

  • 但他得到了 - 1.9999999999909E-5 所以我认为他向我们展示了不同的代码
  • 我认为这是一个错字。我复制了他的代码,得到了一个正数。
猜你喜欢
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多