Home > Software design >  Calculate percentage between two numbers
Calculate percentage between two numbers

Time:05-01

I recently came across an error.

I want to calculate the percentage between two numbers. However, I did not really manage to do it.

Before I asked my question, I visited the following sites:

  1. https://www.codevscolor.com/python-find-change-percentage-two-numbers
  2. How to check change between two values (in percent)?
  3. Calculating change in percentage between two numbers (Python)

None of the above helped. The problem:

I have, for example, two numbers: 3 upvotes and 2 downvote. I want to calculate the percentage of how many people upvoted the message in relation to the downvotes

However, I did not manage to do it.

I want the higher the upvote number gets, the higher the calculated percentage gets.

Example:

3 upvotes and 3 downvotes: 50% upvotes 4 upvotes and 3 downvotes: XX% upvotes (Higher than 50%)

Here is what I have tried to do:

percentage = (data[str(payload.message_id)]['downvote'] / data[str(payload.message_id)]['upvote']) * 100
# The higher it gets, the lower the number gets -> 10 to 6 = 60%

((data[str(payload.message_id)]['downvote'] / data[str(payload.message_id)]['upvote']) * 100) / 2
# Also calculates things wrong -> 16 to 6 = 37.5%

float(data[str(payload.message_id)]['upvote'])-data[str(payload.message_id)]['downvote'])/data[str(payload.message_id)]['downvote'])*100

And some more things. Maybe this is just a simple mistake I made, but I am not seeing it. data[str(payload.message_id)]['upvote'] and data[str(payload.message_id)]['downvote'] are obviously the numbers I saved somewhere.

CodePudding user response:

If you have 2 numbers a,b their percentages must be in relation to their sum a b. If you have 3 upvotes and 3 downvotes,

percentage_upvote = (3 / 6) * 100 = 50%

For your second case (16, 6),

percentage_upvote = (16 / 22) * 100 = 72.73

CodePudding user response:

fraction = data[str(payload.message_id)]['upvote'] / (data[str(payload.message_id)]['upvote']   data[str(payload.message_id)]['downvote'])
print(f"{fraction:.2%}")
  • Related