2016-03-01 124 views
1

我有最難倒的時間試圖自動計算稅收在PHP中。這是我到目前爲止有:計算稅額總額再次PHP設置變量

<?php 
// Formats a number so it appears as such : 55.12, instead of 55.12354 
function invoiceNumFormat($number){ 
    return number_format($number, 2); 
} 

$tax_rate = 7.5; //Sets Tax Rate 

// Retrieves Subtotal, utilitzes NumFormat function to round to hundredths place 
$invoice_subtotal = isset($invoice['invoice_subtotal']) ? invoiceNumFormat($invoice['invoice_subtotal']): 0; 

//Multiplies subtotal against tax rate to retrieve $tax_amount 
$tax_amount = invoiceNumFormat($invoice_subtotal*$tax_rate/100); 

// Shows Grand Total(subtotal + tax) 
$invoice_totalled = $invoice_subtotal + $tax_amount; 

//Displays Totals 
<span>'.$invoice_subtotal.'</span> 
<span>'.$tax_amount.'</span> 
<span>'.$invoice_totalled.'</span> 
?> 

我有一個小計的輸出顯示「3116.88」,這是正確的,但稅收表現爲量。」 32" 和總計是‘3.23’ 。任何人都可以告訴我哪裏出了問題?

+0

我試過你的代碼$ invoice_subtotal = 3116.88; //硬編碼的價值,這導致我罰款,總計:3116.88,稅:233.77,總計:3350.65。所以我認爲,$ invoice_subtotal變量下有一些錯誤的值。 – ameenulla0007

+0

@ ameenulla0007排除了一些錯誤,只要我拿出invoiceNumFormat函數,就會發現所有總計都會出現FINE。現在的問題是,我仍然需要把這一美元的數額... – Steven

+0

美元的金額!你可以清楚這個請.. – ameenulla0007

回答

1

是的!

$invoice_subtotal = isset($invoice['invoice_subtotal']) ? invoiceNumFormat($invoice['invoice_subtotal']): 0; 

問題是在上面的行。

這裏發生的情況是,您在設置小計值時使用了功能invoiceNumFormat,當您通過3116.88時,則返回3,116.88,該值不是整數。

所以更改線路

$invoice_subtotal = isset($invoice['invoice_subtotal']) ? $invoice['invoice_subtotal'] : 0; 
+0

我用你的解決方案,此外我必須有一個$ tax_amount和一個$ tax_amount2(一個需要的函數),以及一個$小計,和$ subtotal2(同樣的事情) 。我根據需要鞭打他們,以獲得我想要的輸出。謝謝! – Steven

+0

這太棒了.. :) @Steven你永遠是受歡迎的.. – ameenulla0007

1

您第一格式的數字,然後計算$tax_amount$invoice_totalled。但通過這種方式,您可以在字符串值上執行操作,因此您可以獲得不想要的值。

您必須執行全部帶浮點值的數學運算並僅在輸出格式化變量。

$invoice_subtotal = $invoice['invoice_subtotal']; 
$tax_amount  = $invoice_subtotal * $tax_rate/100; 
$invoice_totalled = $invoice_subtotal + $tax_amount; 

echo '<span>'.invoiceNumFormat($invoice_subtotal).'</span> 
<span>'.invoiceNumFormat($tax_amount).'</span> 
<span>'.invoiceNumFormat($invoice_totalled).'</span> 
'; 
+0

我希望我能給出2個正確的答案,試過這個,並且它也可以工作! – Steven

+0

@Steven如果您不更改所有**子值,您將獲得稅收金額> 1000.00(即小計= 14000.00)的小計的錯誤結果,因爲小計問題將影響稅額格式(1000.00 => 1,000.00) – fusion3k