【问题标题】:Calculate tax total agains php set variables根据php设置变量计算税收总额
【发布时间】:2016-03-01 17:41:28
【问题描述】:

我正在尝试在 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 = 3116.88 试过你的代码; //硬编码值,结果很好,总计:3116.88,税:233.77,总计:3350.65。所以我认为,$invoice_subtotal 变量下有一些错误的值。
  • @ameenulla0007 进行了更多故障排除,每当我取出 invoiceNumFormat 函数时,发现所有总数都很好。现在的问题是,我仍然需要将其四舍五入到美元金额......
  • 美元金额!!你能说清楚吗..

标签: php


【解决方案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;

【讨论】:

  • 我使用了您的解决方案,此外我还必须有一个 $tax_amount 和一个 $tax_amount2(需要该功能),以及一个 $subtotal 和 $subtotal2(同样的东西)。我根据需要鞭打它们以获得我想要的输出。谢谢!
【解决方案2】:

您首先格式化数字,然后计算 $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>
';

【讨论】:

  • 我希望我能给出 2 个正确的答案,试了下,效果还不错!
  • @Steven 如果不更改 all 子值,则税额 > 1000.00(即小计 = 14000.00)的小计将获得错误结果,因为小计问题会影响税额格式 (1000.00 => 1,000.00)
猜你喜欢
  • 1970-01-01
  • 2016-12-06
  • 2018-09-02
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
  • 2013-11-13
相关资源
最近更新 更多