我正在計算某些東西的費用(貨幣),而PHP在數量應該爲0.00時表現得很奇怪。它以浮點數形式給出最終結果,而不是0。PHP奇怪地減去數字 - 返回長浮動值
在我的數據庫中,我有如下表
id | transaction_total | charge_fees | deposit_fee | amount_to_customer | fees_minus_total_difference
所以,當我去檢查,以確保所支付的費用+量 - 總= 0.00
(96.54 + .25 + 3.20 - 99.99) = 1.4210854715202E-14
爲什麼結果浮動數字,而不是實際零?數字本來是更多的小數位,但我用number_format把它放到2個地方。例如,收費實際上可能是3.19987
number_format(3.19971,2,'.','') //equals 3.20
當我將它保存在我的數據庫中時,它顯示爲3.20。當我在總計/費用檢查的計算中使用它時,結果不是零,儘管接近。
http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding – deceze
切勿使用*貨幣價值浮動點*,除非你不介意失去少量的錢(或者獲得一些,也許)。要麼以美分計算,要麼以像bcmath這樣的任意精度庫來計算。 – deceze
[PHP Math Precision]的可能重複(http://stackoverflow.com/questions/3726721/php-math-precision) – deceze