On many e–commerce sites, often times you will be presented with how much money you could be saving (and the percentage), if you purchase the particular product:
This is a great approach to presenting the customer with important “buying information,” and can often help them make that final decision of “purchase, or forget.”
For Web Developers to display this information, a small mathematical formula is needed.
And, with the help of PHP, you never have to worry if your numbers are accurate. PHP takes care of it all.
Let’s say you have a product that you want to sell for $49.00. That price is a discount from $65.00.
Calculating the amount of savings is easy (subtract the original price from the discount price), but how do we obtain the percentage?
Anyone with a small knowledge of math would tell you to divide the difference by the original.
This is indeed accurate, and then there’s one more step: multiply that result by 100.
So, for our example, we’d subtract 49 from 65, and we end up with 16. Then, we take 16, and divide it by 65 (the original price), and we get an extremely long decimal number. It is something like 0.2461538…. If we then multiply that number by 100, we end up with a more understandable digit: 24.61538...
So, as you can see, the savings percentage for our example numbers is somewhere around 24.6%.
Unfortunately, unless we intentionally round this number, a script result (PHP, for example) will still output the incredibly long decimal.
For our PHP example, we work with a few simple variables:
- Contains the original product price.
- Contains the discounted price.
- Contains the amount of money saved.
- Contains the actual percentage of money saved.
We will assume that the
$discount_price variables have already been set.
Set both the
$savings_percentage variables like this:
$savings = $original_price - $discount_price;
$savings_percentage = round( ($savings/$original_price)*100, 0 );
Most of it is straight–forward math. The PHP
round function is what helps remove excess numbers after the decimal point.
For our real–world example, the result would output 24%, which is nice and round.