根据php集合变量计算税收总额

根据php集合变量计算税收总额,php,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,

我在尝试用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”。谁能告诉我哪里出了问题吗?

是的,我知道了

$invoice_subtotal = isset($invoice['invoice_subtotal']) ? invoiceNumFormat( $invoice['invoice_subtotal'] ): 0;
问题在上面一行

这里发生的是,当设置小计值时,您使用函数
invoiceNumFormat
,当您传递
3116.88
时,它返回的
3116.88
不是整数

所以把线路改成

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

您首先格式化数字,然后计算
$tax\u amount
$invoice\u总计
。但通过这种方式,您可以对字符串值执行操作,因此可以获得不需要的值

您必须对浮点值执行所有数学运算,并仅在输出端格式化变量

$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>
';
$invoice\u subtotal=$invoice['invoice\u subtotal';
$tax\u amount=$invoice\u小计*$tax\u rate/100;
$invoice\u总计=$invoice\u小计+$tax\u金额;
回显“”。发票格式($invoice\u小计)。'
“.invoiceNumFormat(税额)。”
“.invoiceNumFormat($invoice_总计)。”
';

我用$invoice\u subtotal=3116.88尝试了您的代码//硬编码的价值,这导致我罚款,总数:3116.88,税:233.77,总计:3350.65。所以我认为,$invoice\u subtotal变量下有一些错误的值。@ameenulla0007排除了更多的问题,计算出了所有总计,只要我取出invoiceNumFormat函数就可以了。现在的问题是,我仍然需要将其四舍五入到一美元金额…美元金额!!我使用了你的解决方案,另外我必须有$tax\u amount和$tax\u amount2(需要这个函数),还有$subtotal和$subtotal2(相同的东西)。为了得到我想要的产出,我根据需要对它们进行快速调整。谢谢我希望我能给出两个正确的答案,试过这个,它也很有效@Steven如果您不更改所有子值,则对于税额>1000.00(即小计=14000.00)的小计,您将获得错误的结果,因为小计问题将影响税额格式(1000.00=>1000.00)