浮点数——PHP非常小的小数会导致错误


floating point - PHP very small decimals result in error

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

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

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

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


我在论坛上做了一些搜索,看到浮点给PHP适合,但还没有看到一个解决方案或变通,似乎回答我的问题。

我的计算器显示结果应该是0.00002

使用number_format:

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

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