Reputation:
I want to calculate what is $x percentage of a $total. $x could be 15%, 20%, etc, and $total could be 1000, 2000, etc. So I'd want the 15% of 1000, for example.
What is the formula for calculating this? (I know this isn't exactly a coding question but I'm coding this feature and need help!
Upvotes: 25
Views: 50477
Reputation: 1658
Are you looking for percentage IN a value, or percentage OF a value?
The difference is that percentage of is based on the original value, while percentage in the percentage assumes that the total already includes your percentage, and the base is correspondingly lower.
For example, percentage-of calculation would be: "If I invest $1000 at 15%, how much will I receive after one year?" The answer is of course $150 Percentage-in calculation would be "I had this 15% investment for a year, and it is now worth $1000. How much did I start out with?" The answer for that is NOT $850 as one might naively expect.
Since you mentioned total, I suspect you are looking for percentage IN the total. To derive the formula for it, you have to work backwards from DaEagle's formula:
His version was:
NewValue = $1000 * 15%
The total thus would be:
Total = $1000 * (1 + 0.15)
For percentage-in calculation, you know the total, but you don't know the starting value:
$1000 = StartValue * (1 + 0.15)
Solving that for StartValue:
StartValue = $1000/(1 + 0.15)
StartValue = $869.57
Upvotes: 0
Reputation: 61
You must consider the case where the totalAmount is zero or else you risk a runtime error (division by zero). And also, you will probably want to round the answer.
#A Perl one liner to to do this is:
$pc=$tot>0 ? sprintf('%.0f', $x/$tot*100 ).'%' : 'N/A';
Upvotes: 0
Reputation: 123473
(actual / available) * 100 = percent // start
actual / available = percent / 100
actual = (percent / 100) * available // finish
E.g. 15% of 1000
actual = (15 / 100) * 1000
actual = 0.15 * 1000
actual = 150
Upvotes: 35
Reputation: 242
Don't know if I'm missing something here but if you just want the percentage of a number it's just multiply it by the percentage and divide by 100:
NewTotal = Total * Percentage / 100
IE:
NewTotal = 1000 * 15/100
or
NewTotal = 1000 * 0.15
Upvotes: 1
Reputation: 61233
formulas:
percentage = partialAmount / totalAmount
totalAmount = partialAmount / percentage
partialAmount = percentage * totalAmount
note that percentage is normally a decimal number between 0 and 1
Upvotes: 5
Reputation: 32632
Given X and Y, X% of Y is X * Y/100. If using integer arithmetic, make sure you do (X * Y)/100, not (X / 100) * Y.
15% of 1000 is (15*1000)/100, which is 150.
Upvotes: 4