December 11th, 2007 at 7:17 am

Calculating the V.A.T. amount from the total price

Sometimes you need to calculate the V.A.T. (for Germans: MwSt.) from a given total price. This is, for example, if you charge an arbitrary total price, but need to display the V.A.T. percentage along with the V.A.T. amount. For this purpose, you can use the following code:

<?php
	function calc_vat_amount_from_total($total, $vat)
	{
		$total = (float)$total;
		$vat = (float)$vat;
 
		if (!$total || !$vat) return false;
 
		$net = $total / (float)('1.'.$vat);
		$vatAmount = $total - $net;
 
		return sprintf("%01.2f", $vatAmount);
	}
 
	$total = '35.00'; // It's a string, but could also be a float or int.
	$vat = '19'; // dito
 
	$vat_amount = calc_vat_amount_from_total($total, $vat);
	echo "The ticket fare of $total &#8364; contains $vat% V.A.T. ($vat_amount &#8364;).";
 
?>