1

可能重复:
限制浮点精度问题的实践

当我将新的 totalSubs 列表添加到运行总计时,PHP 返回一个奇怪的值。我生成了以下输出(见第 40 行):

1 The total currently '0' (integer) + new TotalSub '-26969.55' type(double) = total '-26969.55'
2 The total currently '-26969.55' (double) + new TotalSub '249.6' type(double) = total '-26730.05'
...
39 The total currently '-164.89' (double) + new TotalSub '61.95' type(double) = total '-112.94'
40 The total currently '-102.94' (double) + new TotalSub '98.71' type(double) = total '-5.3300000000009'
41 The total currently '-5.3300000000009' (double) + new TotalSub  '50' type(double) = total '45.769999999999'

PHP生成是:

echo ($count++) . " The total currently '$totalTrans' (".gettype($totalTrans).") + new TotalSub '$totalVar' type(".gettype($totalVar).") = total '" . ($totalTrans + $totalVar) ."'<br />";

如何修复 00000000009?

4

2 回答 2

1

用于printf解决该问题并使您的代码同时呈现:

printf("%d The total currently '%.2f' (%s) + new TotalSub '%.2f' (%s) = total (%.2f)<br />",
       $count++,
       $totalTrans,
       gettype($totalTrans),
       $totalVal,
       gettype($totalVar),
       $totalTrans + $totalVar);
于 2013-01-29T12:54:44.123 回答
1

从我能看到的。
尝试将输入数据乘以 100,然后在最后将总数除以 100。

乘以 1 或 10 很可能不会纠正它,这可能是由于 2 位小数和使用 100 值现在是整数(整数

请记住浮点数据类型(例如DOUBLE)不代表精确的数字并且是近似的。

您将来可以bcmath()用于数学计算,因为 using number_format() 与 using () 没有区别,round但不将其作为字符串返回。
http://php.net/manual/en/book.bc.php

于 2013-01-29T12:51:45.270 回答