Skip to content

Instantly share code, notes, and snippets.

@byjml
Created October 12, 2011 09:09
Show Gist options
  • Save byjml/1280716 to your computer and use it in GitHub Desktop.
Save byjml/1280716 to your computer and use it in GitHub Desktop.
Calculates the amount in the invoice and returns a new amount with discount and tax added, the total also will be rounded to 2 decimal places. Discount and tax will only be applied when available.
<?php
/**
* Calculates the amount in the invoice and returns a new amount with discount and tax added,
* the total also will be rounded to 2 decimal places. Discount and tax will only be applied
* when available.
*
* USAGE:
* <code>
* // Example 1: Subtract discount from subtotal, add tax and return the grand-total.
* calc_invoice( 500, 0.5, 5 );
*
* // Example 2: There's no discount, add tax to the subtotal and return the grand-total.
* calc_invoice( 500, 0, 5 );
*
* // Example 3: There's a discount but tax was not provided. Return the subtotal minus the discount as a grand-total.
* calc_invoice( 500, 0.5, 0 );
*
* // Example 4: There's no discount and tax. Return the subtotal as a grand-total.
* calc_invoice( 500, 0, 0 );
* </code>
*
* Note: to print the result you can set the fourth param to true.
*
*
* @param float|int $subtotal The total amount of the invoice fields.
* @param float|int $discount The discount applied to the amount in the invoice fields.
* @param float|int $tax The tax applied to the amount in the invoice fields.
* @param bool $echo Whether to return or print the result.
* @return float|int $total The calculation of the total amount in the invoice including discount and tax (if available).
*/
function calc_invoice( $subtotal, $discount, $tax, $echo = false ) {
/* If there's a discount, subtract the discount from the subtotal. */
$discount = $subtotal - ( $discount * ( $subtotal / 100 ) );
/* Return the descount with precision. */
$discount = round( $discount, 2 );
/* Calculate the discount + the tax. */
$total = $discount + ( $tax * ( $discount / 100 ) );
/* Return or print the total after calculating the descount and the VAT. */
if ( $echo == true )
echo round( $total, 2 );
else
return round( $total, 2 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment