Stuart Stuart - 3 months ago 17
Javascript Question

math formula for rating system

I would like to know if there would be a better way to create my

stars
variable based on a percentage value.

All I need is to determine the rating 1, 1.5, 2, 2.5, etc stars based on the percentage value.

I've done it with a switch statement, but wondered if there was a math formula that could do this?

Just seems a little long winded programmaticly to do it this way?

var stars = 0;

switch (true) {
case score === 100:
stars = 5;
break;
case score >= 90:
stars = 4.5;
break;
case score >= 80:
stars = 4;
break;
case score >= 70:
stars = 3.5;
break;
case score >= 60:
stars = 3;
break;
case score >= 50:
stars = 2.5;
break;
case score >= 40:
stars = 2;
break;
case score >= 30:
stars = 1.5;
break;
case score >= 20:
stars = 1;
break;
case score >= 10:
stars = 0.5;
break;
case score >= 0:
stars = 0;
break;
}


i'll admit my math skills are not very good (i'm dyslexic with numbers) so sorry if my question offends those that are strict about trying things yourself, but this is just frying my brain!

Thanks in advance for any help given!

Answer

Simple:

stars = Math.floor(score / 10) / 2