Reputation: 697
I am having the darndest time trying to auto calculate taxes in php. This is what I have so far :
<?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>
?>
I have an output of a subtotal showing "3116.88" which is correct, but the tax showing for that amount is ".32" and the grand total is "3.23". Can anyone tell where I have gone wrong?
Upvotes: 1
Views: 1062
Reputation: 11689
You first format numbers, then calculate $tax_amount
and $invoice_totalled
. But by this way you perform operations on string values, so you can obtain undesired values.
You have to perform all math operations with float values and to format variables only at the output.
$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>
';
Upvotes: 1
Reputation: 2683
yup got it!
$invoice_subtotal = isset($invoice['invoice_subtotal']) ? invoiceNumFormat( $invoice['invoice_subtotal'] ): 0;
the problem is in the above line.
what happens here is, you utilized the function invoiceNumFormat
when the subtotal value is set, when you pass 3116.88
then it returns 3,116.88
which is not an integer.
so change the line to
$invoice_subtotal = isset($invoice['invoice_subtotal']) ? $invoice['invoice_subtotal'] : 0;
Upvotes: 1