Posts tagged 'percent'

Calculate percent from value

Posted on August 31, 2008, Filled under PHP,  Bookmark it

Here’s how you can calculate the percent from a value.

<?php
/* Credits: http://www.bitrepository.com */

// example: number of employees in a company's department (Marketing)
$value = '20';
// total employees that company has
$total = '500'; 

$percent = number_format(($value * 100) / $total);

// percent of employees from the Marketing Department.
echo $percent.'%';
?>

Calculating value from percent

Posted on August 31, 2008, Filled under PHP,  Bookmark it

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

Here’s the script which calculates the special discount value and the final price:

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

Any comments and suggestions regarding this script are welcomed.