You can achieve what you want, as shown below,
var ratingValue = 3.489, rounded = (ratingValue | 0); var decimal = ratingValue - rounded, $rating = $(".rating"); for (var j = 0; j < rounded ; j++) { $rating.append('<i class="fa fa-star" aria-hidden="true"></i>'); } if(decimal) { $rating.append('<i class="fa fa-star-half" aria-hidden="true"></i>'); }
Change according to your new requirement,
No need for two different cycles (simple math)
var ratingValue = 3.9, rounded = (ratingValue | 0); for (var j = 0; j < 5 ; j++) { $(".rating").append( '<i class="fa '+ ((j < rounded) ? "fa-star" : ((((ratingValue - j) > 0) && ((ratingValue - j) < 1)) ? "fa-star-half-o" : "fa-star-o")) +'" aria-hidden="true"></i>'); }
And to make the code more readable, we can do it,
var ratingValue = 1.9, rounded = (ratingValue | 0), str; for (var j = 0; j < 5; j++) { str = '<i class="fa '; if (j < rounded) { str += "fa-star"; } else if ((ratingValue - j) > 0 && (ratingValue - j) < 1) { str += "fa-star-half-o"; } else { str += "fa-star-o"; } str += '" aria-hidden="true"></i>'; $(".rating").append(str); }
Rajaprabhu aravindasamy
source share