News for hackers. Stuff that matters.
Re:How to Make Easy & Flexible Star Ratings by llgrrl_ on Friday October 14, 2011 @05:25PM (#3113018)
This is the code that should go to the server side for calculating star ratings:

Star Ratings

I’ve been awfully busy programming lately. My Django-based side project is coming along well and I hope to have it ready for use in a few weeks. Please don’t ask more about it, that’s really all I can say for now. Anyways, I came across an interesting little math problem today and was hoping some skilled programmers out there could come up with a more elegant solution than mine.

Problem: Star Ratings

People can rate cheeseburgers on my website with a star rating of 0-5 stars (whole stars only), 5 being mighty tasty and 0 being disgusting. I would like to show the average of everyone’s ratings of a particular cheeseburger to the nearest half star. I have already calculated the average rating as a float (star_sum) and the total number of people that rated the particular cheeseburger (num_raters). The result should be stored as a float in a variable named “stars.”

My Solution (in Python):

  # round to one decimal place and
  # separate into whole and fractional parts
  parts = str(round(star_sum/num_raters, 1)).split('.')
  whole = int(parts[0])
  frac = int(parts[1])

  if frac < 3:
    ___frac = 0
  elif frac > 7:
    ___frac = 0
    ___whole += 1
  else:
    ___frac = 5

  # recombine for a star rating rounded to the half
  stars = float(str(whole)+’.'+str(frac))
Mmmm… In-N-Out Burgers… Please leave a comment if you’ve got a better solution.
Re:How to Make Easy & Flexible Star Ratings by teej on Friday October 14, 2011 @06:09PM (#3113152)
Please don't do that. Here's a one liner:

    round( 2.0 * star_sum / num_raters) / 2.0
Re:How to Make Easy & Flexible Star Ratings by jeiting on Friday October 14, 2011 @06:21PM (#3113184)
Have you tried a recursive solution?

def round_to_half(x): if ( x < 1) { if (x < 3) { return 0; else if (x > 7) { return 1.0; } else { return 0.5 } } else { return round_to_half(x/10); } }

x = star_sum/num_raters dec = round_to_half(x) x = floor(x/10) + dec

This way you look smarter for using recursion.

Re:How to Make Easy & Flexible Star Ratings by Aloisius on Friday October 14, 2011 @06:13PM (#3113164)
Can't you just internally multiple everything by 2, average the whole thing, round, then divide by 2 to get half point ratings?

  stars = round(star_sum * 2 / num_raters)/2