Friday, November 26, 2010

Calculating value from percent

This short tutorial is aimed to help you how to calculate the percent value from a total. Let’s suppose you have a e-commerce site and you offer discounts to the customers. You need to show them how much is the discount value worthing

Here’s a sample from an order total:
Notebook’s price: $1,300
Our special discount: 30% (-$390)
Final price: $910

 <?php
$percent = '30'; // without %
$total = '1300'; // initial value

/* Calculate $percent% from $total */
$discount_value = ($total / 100) * $percent;

$final_price = $total - $discount_value;

// Format numbers with number_format()

$total = number_format($total);
$discount_value = number_format($discount_value);
$final_price = number_format($final_price);

echo "Notebook's price: $".$total."<br />Our special discount: <strong>".
$percent."%</strong> (-$".$discount_value.")<br />Final price: $".$final_price;
?>

No comments:

Post a Comment