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:
  1. <?php
  2.    
  3.     function calc_vat_amount_from_total($total, $vat)
  4.     {
  5.         $total = (float)$total;
  6.         $vat = (float)$vat;
  7.  
  8.         if (!$total || !$vat) return false;
  9.  
  10.         $net = $total / (float)('1.'.$vat);
  11.         $vatAmount = $total - $net;
  12.  
  13.         return sprintf("%01.2f", $vatAmount);
  14.     }
  15.  
  16.     $total = '35.00'; // It's a string, but could also be a float or int.
  17.     $vat = '19'; // dito
  18.  
  19.     $vat_amount = calc_vat_amount_from_total($total, $vat);
  20.     echo "The ticket fare of $total &#8364; contains $vat% V.A.T. ($vat_amount &#8364;).";
  21.  
  22. ?>

Leave a Comment