Hello Everyone!

I have been working on a project recently and that project required a profit margin calculator. I had built a few other types of calculators before, never one to calculate profit margins.

It took me a little digging and some web searching to figure out what I need to do as I am not the best at math!

Now I want to share my findings with you on how to build your own profit margin calculator! Now I won’t be building anything in HTML or Javascript in this post for our calculator. I will just show you the steps to take to do the calculations.

## The Code

Let’s dive right in shall we?

To figure our profit margin of to number this is pretty straight forward, I will show you the formula then how to reproduce in code.

## The Formula

Markup Percentage = Profit / Cost = 25 / 100 = 25%

var cost = 10; var sale = 20; var margin = (sale - cost) / cost * 100 // margin = 100

Ahh that was pretty easy, right? As you can see with only a few lines of code we have figured out what the percentage of margin is of two numbers!

## Calculate Sale Price

Now, what if we need to figure out what the sale price would be of say $12.50 with a profit margin of 60% is? We can do this pretty easily too!

var cost = 12.50; var sale; var margin = 60; sale = (margin / 100) * cost + cost; // sale = 20

Hopefully, you understand what we did there. If not I will do my best to explain.

We started at a cost of $12.50 and wanted to know what the sale price would be with a 60% markup. To do this we take the 60% markup and divided by 100 this gives us 0.6. This is the fraction we need to calculate our sale price.

Now we take 0.6 and multiply by the cost which now gives us 7.5 which is 60% of 12.5. We can check this by dividing this by 12.5 which will give us 0.6 or 0.6X100=60%

The last thing to do is add that to the cost to get our sale price so, 12.5 + 7.5 = sale price of 20

I deceided to wrap these in a couple function to make using them a bit easier:

// Calculate Margin function calcMargin(price, cost){ var cost = Math.round(cost*100)/100; var price = Math.round(price*100)/100; var diff = price - cost; var margin = (diff / cost) * 100 return margin; } // Calculate Sale Price function calcSalePrice(cost, margin){ var cost = Math.round(cost*100)/100; var margin = Math.round(margin*100)/100; var sale = (margin / 100) * cost; var number = sale + cost; return number; }

## Final Thoughts

As you can see this wasn’t too difficult to figure out and for someone who isn’t the best at math I had fun doing this!

Till Next Time, Keep Coding & Have Fun!