Stuart
Stuart

Reputation: 1574

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!

Upvotes: 3

Views: 641

Answers (3)

Deepak Kumar
Deepak Kumar

Reputation: 21

var result = Math.floor(score * 0.1) / 2
stars = score > 100 ? 0: result 

Upvotes: 1

Abhishek Priyadarshi
Abhishek Priyadarshi

Reputation: 581

please try this

stars = score > 100 ? 0: Math.floor(score * 0.1) / 2

Upvotes: 4

neelsg
neelsg

Reputation: 4842

Simple:

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

Upvotes: 6

Related Questions