2016-11-15 56 views
0

我從我的數據庫中獲取值列表,並添加它們以獲得所有行的總和。 PHP沒有正確添加,我無法弄清楚爲什麼。我正在用我正在做的事情來工作。結果應該爲零,但PHP計算結果爲$ -1.78。什麼是錯的以下內容:添加值列表的PHP不能正確總計

public function testAddition() 
{ 
    $data = ['23.21','-38.20','14.99','0.00']; 
    $total = 0; 
    foreach ($data as $value) { 
    $total += round(floatval($value), 2); 
    var_dump($value); // value to add 
    var_dump($total); // new total 
    } 
    // PHPunit results a success to zero, this is wrong, $total = -1.776... 
    $this->assertEquals(0, $total); 
} 

輸出如下:

string(5) "23.21" // value to add 
float(23.21) // new total 
string(6) "-38.20" // value to add 
float(-14.99) // new total 
string(5) "14.99" // value to add 
float(-1.7763568394003E-15) // <-- this is wrong, should be zero 
string(4) "0.00" // value to add 
float(-1.7763568394003E-15) // new total 

回答

1

結果是-1.7763568394003E-15或0.0000000000000017763568394003;當「四捨五入」= 0.00時。這只是一個計算數字爲「浮動」的問題 - 幾乎總是會有小的剩餘部分

解決方法是舍入結果以及?或者乘以100並且使用(int)然後再除以100(儘管理論上可以留下餘數)

另外,雖然它不回答你的問題,但你不需要floatval,你可以只需使用$total += round($value, 2);作爲PHP自己爲您投射。

+0

謝謝在發佈之後發現我的錯誤。我們的HTML表單將使用'12,345.67'格式化貨幣。我們有一個通用的例程,在轉換爲浮點數之前從輸入字符串中去除非數字,這是剝離指數。愚蠢的問題。 – user3720435