我有一個小問題來獲得正確的發票總額。01價值對總金額的差異
我對SQL表
unit_price decimal(25,2)
vat varchar(55)
total_novat decimal(25,2)
total_vat decimal(25,2)
grand_total decimal(25,2)
php腳本來獲取值是:
$discount = 2
$total_novat += qty * unit_price/discount
$total_vat = qty * vat/100
$grand_total = total_novat + total_vat
好,現在如果我做這個簡單的腳本上值的結果是:
unit_price: 1 * 241.14/2 = 120.57
total_novat: 120.57 * 24/100 = 28.94
grand_total: 120.57 + 28.94 = 149.51
問題是,當我把這個代碼在php中的結果是149.50而不是149.51
任何幫助表示讚賞。
完全腳本來執行計算:在PHP腳本
<?php
$inv_total_no_tax = 0;
for($i=1; $i<=TOTAL_ROWS; $i++){
if($this->input->post($quantity.$i) && $this->input->post($product.$i) && $this->input->post($unit_price.$i) && $this->input->post($discount.$i)) {
$tax_id = $this->input->post($tax_rate.$i);
$tax_details = $this->sales_model->getTaxRateByID($tax_id);
$taxRate = $tax_details->rate;
$taxType = $tax_details->type;
$tax_rate_id[] = $tax_id;
$inv_quantity[] = $this->input->post($quantity.$i);
$inv_product_code[] = $this->input->post($product.$i);
$inv_unit_price[] = $this->input->post($unit_price.$i)/$this->input->post($discount.$i);
$inv_unit_discount[] = $this->input->post($discount.$i);
$inv_gross_total[] = (($this->input->post($quantity.$i)) * ($this->input->post($unit_price.$i))/($this->input->post($discount.$i)));
if($taxType = 1) {
$val_tax[] = (($this->input->post($quantity.$i)) * ($this->input->post($unit_price.$i))/($this->input->post($discount.$i)) * $taxRate/100);
} else {
$val_tax[] = $taxRate;
}
if($taxType = 1) { $tax[] = $taxRate."%"; } else { $tax[] = $taxRate; }
$inv_total_no_tax += (($this->input->post($quantity.$i)) * ($this->input->post($unit_price.$i))/($this->input->post($discount.$i)));
}
}
$total_tax = array_sum($val_tax);
$total = $inv_total_no_tax + $total_tax;
回合選項我改變了小數的MySQL爲varchar。
if i use $total = round($inv_total_no_tax + $total_tax, 2); the result is: 149.5
if i use $total = round($inv_total_no_tax + $total_tax, 3); the result is: 149.501
解決方案:
之前將其引入到mysql我已經申請此字符串。
number_format($value, 2, null, '');
因爲您正在處理浮點數。谷歌對於「浮點錯誤」來看看很多話題。 – zerkms
你是如何處理舍入數字的? 'total_noval = 28.9368' – datasage
[每個程序員應該知道什麼關於浮點算術或 爲什麼我的數字不會累加?](http://floating-point-gui.de/) – 2013-01-14 20:34:50