Calculate percentage of votes

Asked

Viewed 2,869 times

0

Hello, I have a voting system for a news that contains like and deslike.

However, I would like to calculate a percentage of this news, based on the amount of votes, positive or negative. For example: when I don’t have any votes it would be 100%, or with 10 positives it would be 100%. How can I do this in php?

  • Your question is about the account? It’s not clear.

  • I record the votes, like and deslikes. I want to make a calculation to know the percentage of news based on those votes. That is, to give a note the news...

  • 1

    dislike + like = Total. (Dislike / Total) * 100 = % dislike. (Like / Total) * 100 = % like. If you can post some code snippets it is better to exemplify.

1 answer

5


Well, I believe that’s it:

EDIT:

As commented by Bacco, there is a risk of division by zero that can be inhibited with an IF. Thus:

$like = 3;
$dislike = 10;
$total = $like + $dislike;
if($total != 0){
  $porcentagemLike = ($like / $total) * 100;
  $porcentagemDislike = ($dislike / $total) * 100;
} else {
#caso nao tenha like ou dislike, seta like como 100% e dislike como zero;
  $porcentagemLike = 100;
  $porcentagemDislike = 0;

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.