Reputation: 323
How do I increase or decrease an "X" number by a certain amount of percentage say, 2% or 3%?
Case scenario: My value is 5 - I want to increase this number by 2% - so the final value will be 5.1 after 2% percentage increase.
And the same would be if I want to decrease this number by an "X" percentage.
I hope that makes sense, thank you.
Upvotes: 1
Views: 11188
Reputation: 2611
To calculate a percentage in Python, use the division operator (/) to get the quotient from two numbers and then multiply this quotient by 100 using the multiplication operator (*) to get the percentage.
y=int(input("Enter Percentage: "))
x=5
x += (x * y/100)
print(x)
Output:
Enter Percentage: 2
5.1
For Decreasing Value:
y=int(input("Enter Percentage: "))
x=5
x -= (x * y/100)
print(x)
Output:
Enter Percentage: 2
4.9
Upvotes: 3
Reputation: 12663
If you want to increase by a percent, multiply the number by (1+{percent}). To decrease by a percent, multiply the number by (1-{percent})
. Given your example:
5*(1+0.02)=5*1.02=5.1
5*(1-0.02)=5*0.98=4.9
.Upvotes: 1
Reputation: 71542
A percent is just a fraction of 100, so multiply by 1 + your percent over 100:
>>> x = 5
>>> x *= (1 + 2/100)
>>> x
5.1
Another way to think of it is incrementing x
by x
times that percent (these operations are algebraically equivalent):
>>> x = 5
>>> x += (x * 2/100)
>>> x
5.1
Upvotes: 1