Calculate the 5 star rating for products in C#.NET

In the current eCommerce market showing customer product rating is important on your website which enables the customer to make few decisions on the product before buying it or comparing it with similar products. To display the product rating, you must enable the rating on your website.

Enabling the rating on the website is not our context now in this article, rather we will discuss on how to calculate the overall product rating from all customer ratings. Many people will have misunderstood about rating calculation where they think that product rating is an average rating among all customer ratings.

Which is incorrect! Oh, is it!! Then? What is correct? The answer is weighted average.

Calculate 5 star rating

In the weighted average, you should weigh each rating against the number of votes and perform the average on it.

So, the formula is, sum of weighted rating for each star / total ratings.

Product Rating = (5*votes + 4*votes + 3*votes + 2*votes + 1*votes) / total votes

Let’s do an example by considering the above picture.

Star
Ratings/Votes
Weighted Rating
5
12,801
64,005
4
4,982
19,928
3
1,251
3,753
2
429
858
1
1,265
1,265
Total
20,728
89,809

Product Rating = 89,809 / 20,728 = 4.3

Now it’s time to apply this SIMPLE formula to our C# code to calculate the rating. For demonstrating purpose, I am going to do the same in console application. Typically you can apply the same formula anywhere in any language.

Here is the method GetRating() to give the product rating.

        private static double GetRating()
        {
            int star5 = 12801;
            int star4 = 4982;
            int star3 = 1251;
            int star2 = 429;
            int star1 = 1265;

            double rating = (double)(5 * star5 + 4 * star4 + 3 * star3 + 2 * star2 + 1 * star1) / (star1 + star2 + star3 + star4 + star5);

            rating = Math.Round(rating, 1);

            return rating;
        }

        static void Main(string[] args)
        {
            double rating = GetRating();
            Console.WriteLine("Your product rating: " + rating);
            Console.ReadKey();
        }

Hope this helps to you understanding about the product rating calculation and applying the same in C#.NET.

Any questions? Let’s use the below comment box to discuss. Thank you once again for reading this article.
Calculate the 5 star rating for products in C#.NET Calculate the 5 star rating for products in C#.NET Reviewed by Srinivasa Rao Dhulipalla on March 18, 2018 8:19 PM Rating: 5

No comments:

Powered by Blogger.