Add VAT to Price - php

I have 2 variables: $vatRate and $priceExVat. I want to create another variable named $endPrice which adds the VAT on. I have no clue on how to do this, and am a begginner at PHP so I would like to have a code example ;)
$priceExVat == $_POST['priceExVat'];
$vatRate = $_POST['vatRate'];
rtrim($vatRate ,'%');
$endPrice = ($vatRate * $priceExVat) + $priceExVat;
echo $endPrice;
EDIT: Above is the non-working code which returns a 0

To break it down in full:
<?php
$vatRate = 20; // This must be the percentage VAT rate. e.g.: 20, 17.5.
$priceExVat = 10;
$vatComponent = ($priceExVat / 100) * $vatRate;
$endPrice = $priceExVat + $vatComponent;
echo 'The resultant price is £' . number_format($endPrice, 2);
?>
Incidentally, you may require the VAT portion at a later date, so if you're using this in any non-trivial manner you should really store the base (i.e.: pre-VAT) price and then apply the VAT rate and round accordingly for the purposes of output.
Additionally, you may also want to allow for multiple VAT rates, as not all goods are taxed at 20% in the UK. (Some are exempt, some are taxed at the "reduced" 5% rate, etc.)

$endPrice = ($vatRate * $priceExVat) + $priceExVat;
or
$endPrice = (1+$vatRate * $priceExVat);
Example
$vatRate = 0.07;
$priceExVat = 100.00;
Since getting -3
All the answer is somehow wrong if the value is string 20%
$endPrice = ((int)$vatRate/100)*$priceExVat)+$priceExVat;

This is how it should be done:
function vat($ex_vat,$vat = 20.0)
{
return round($ex_vat+ ((double)$vat*($ex_vat/100)),2);
}
Example:
$withVat = vat(80,20); //£0.80 > £0.96

Assuming $vatRate is specified as percentage.
$endPrice = $priceExVat * $vatRate/100

$vatRate = "20%";
$priceExVat = 100;
$endPrice = (intval($vatRate) / 100) * $priceExVat + $priceExVat;

Related

PHP Mathematical Equation With Percentages

How can I write this equation.
Pretty much here is what I have
(float) $total = (float) $product_price * (float) $percentage;
return (float) $total;
Although now I need to add a country percentage. Therefore if the country percentage is 10% I need to add 10% onto the current total and return it.
I use the variable $country_percentage
If I understand correctly, you want to add the percentage (tax?) to the total. If the $country_percentage is the integer '10', that would equate to '0.10'
($total * (1 + ($country_percentage / 100))
Which would be ($total * 1.10)
You use math, my friend. If your percentage is a string, remove the % symbol with str_replace() and then parse that value using intval($int) or floatval($float). That'll give you a number to work with, 10 for example.
Then you divide your country percentage by 100
10/100 = 0.1
Finally, you multiply your product price by the above value +1.
So:
//if $percentage is a string with '%' in it
$percentage = (floatval( str_replace("%", $percentage) );
$percentageNum = ($percentage/100) + 1;
$total = $product_price * $percentageNum;

Calculate tax total agains php set variables

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?
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;
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>
';

How to solve floating 0.01 value on percentage discount

I'm facing some troubles with .01 values at the end of calculation and i would like to ask if someone has passed trough this issue and can give me a hand to solve mine.
I have this situation:
$total = '319.00';
$discount = '99.00';
$percentage_discount = number_format((1+($discount/$total)) * 100 - 100, 2, '.', '');
echo $percentage_discount . " %<br>";
echo $discount . "<br>";
echo number_format($total * (1-($percentage_discount / 100)), 2, '.', ''); //echo total
Result:
31.03 %
99.00
220.01
The result i need is The right percentage to get the final total value with 220.00
I know that on Magento VAT calculation was a problem similar to this, the final decimals floating was an issue from the beginning and hard to solve, but maybe some experienced person has solves this.
Remove number_format() on $persentage_discount, i.e. leave it as is:
$percentage_discount = ((1 + ($discount / $total)) * 100 - 100);
Otherwhise you are making double round during calculations and final result is 220.0143 because of that. If you want to show $persentage_discount somewhere, use printf().
Update: just simplify the task and separate displays from real calculations:
<?php
$total = '319.00';
$discount = '99.00';
$percentage_discount = ($discount / $total) * 100;
$final = $total * (1-($percentage_discount / 100));
printf('%.2f<br>', $total);
printf('%.2f<br>', $discount);
printf('%.2f%%<br>', $percentage_discount);
printf('%.2f<br>', $final);
?>
output:
319.00
99.00
31.03%
220.00
intval() will do the trick. try it and let me know
echo $new=number_format($total * (1-($percentage_discount / 100)), 2, '.', '').""; //echo total
echo intval($new);

Representing percentage amounts for rate calculations in PHP

I'm working with a few financial formulas that involve float's and rates in percentages, and i'm having a little bit of problems trying to represent these values in my PHP code. Should i use BC Math? Should i divide all my percentages by 100? How would you represent the following formulas in PHP?
e.g: Amount has a tax amount of 8% and an interest rate of 1% a day. Given i want to borrow X amount and pay in 15 days, divided in 3 installments, how much per installment and total payback?
totalTax = amount * 0.08
totalAmount = (amount + totalTax)
interest = totalAmount * 0.01 * 15
perInstallment = totalAmount + totalInterest / 3
The crucial PHP function is number_format(). I'm also casting the type to (float) inside my custom function. As always, test this code. I'm curious if you find any edge cases where this math doesn't sync up with your financial calculations. It passed my tests...
function formatCurrency($input){
$result = number_format((float)$input, 2, '.', ',');
return $result;
}
$amount = 6458.56;
$totalTax = $amount * 0.08;
$totalAmount = $amount + $totalTax;
$interest = $totalAmount * 0.01 * 15;
$perInstallment = ($totalAmount + $interest) / 3;
echo 'Principal = $'.formatCurrency($amount).'<br/>';
echo 'Total Tax = $'.formatCurrency($totalTax).'<br/>';
echo 'Total Amount = $'.formatCurrency($totalAmount).'<br/>';
echo 'Total Interest = $'.formatCurrency($interest).'<br/>';
echo 'Each Installment = $'.formatCurrency($perInstallment).'<br/>';
Attention with your financial operations: 15 days with 1% a day
is not 15% but 16.1 %. Better use pow() function instead of multiply operator.
In PHP (run in command line, for example):
<?
$amount = 1000.0 ;
$tax = 1.08 ; // 8%
$interestPerDay = 1.01 ; // 1%/day
$days = 15 ;
$totalAmount = ($amount * $tax);
$totalAmountWithInterest = $totalAmount * pow($interestPerDay, $days) ;
$perInstallment = $totalAmountWithInterest / 3;
printf("Initial amout: %.2f\n", $amount);
printf("Amount tax inc.: %.2f\n", $totalAmount);
printf("Total amount: %.2f\n", $totalAmountWithInterest);
printf("Total interest: %.2f\n", $totalAmountWithInterest - $amount);
printf("Per installment: %.2f\n", $perInstallment );
Gives:
Initial amout: 1000.00
Amount tax inc.: 1080.00
Total amount: 1253.85
Total interest: 253.85
Per installment: 417.95
According to #larsAnders, it now needs currency conversion.

multiple 2 decimal place figure by a percentage

A have price data stored like this: 10.25
And percentage data like this 1.1100 (1.00%)
I need a function that accurately multiplies the price by the percentage. (in php)
Thanks
You should never store currency as a decimal. Always use intergers.
What is wrong with $money * ($percentage / 100)
It would probably be best if you split the storage of your percent data into two different fields if possible. But this will do what you're looking for, I believe. I split it into two functions - "convertPercentageDataToDecimal" extracts the percent from your data and converts it to a decimal, then "convertPercentageDataToDecimal" simply multiplies the price by the percent.
<?php
$price = 10.25;
$percentageData = "1.1100 (1.00%)";
function multiplyPriceByPercentageData($price, $percentageData) {
$percent = convertPercentageDataToDecimal($percentageData);
return $price * $percent;
}
function convertPercentageDataToDecimal($percentageData) {
$start = strpos($percentageData, '(') + 1;
$length = strpos($percentageData, '%') - $start;
$percent = substr($percentageData, $start, $length);
return $percent / 100;
}
var_dump(convertPercentageDataToDecimal($percentageData));
var_dump(multiplyPriceByPercentageData($price, $percentageData));
// output:
// float(0.01)
// float(0.1025)

Categories