Convert rating value to visible stars using fontawesome icons Just curious if there is a more elegant way to perform the same result. I have a calculated rating which I want to convert to visible stars using fontawesome icons. Max rating is 5. I am rounding the rating to the nearest .5.
Done in js given a rating called data (sum of all votes / number of votes).

//example, can be anything from 0-5 after being computed
data = 3.65;

//get rating in nearest .5 value (this is how many stars need to be yellow)
rating = yellow = (Math.round(data*2)/2).toFixed(1);

//how many stars need to be white
white = 5 - rating;

output = '&lt;div title="'+rating+'"&gt;';

//output full yellow stars
while (yellow &gt;= 1) {
    output += '&lt;i class="fa fa-star text-yellow"&gt;&lt;/i&gt;';
    yellow--;
}
//what is left can either be .5 or 0... if .5 output half yellow star
if (yellow == .5) {
    output += '&lt;i class="fa fa-star-half-o text-yellow"&gt;&lt;/i&gt;';
}
//output remaining full white stars
while (white &gt;= 1) {
    output += '&lt;i class="fa fa-star-o text-yellow"&gt;&lt;/i&gt;';
    white--;
}

return output + '&lt;/div&gt;';


The above does what I want it to, but I have to believe there is a better approach to get the same result.
I recently implemented this same thing, here's what I used. Main difference: Let the for loop do the math for you. By the end of the first loop, if there is half a star it will be in the i variable. Use an array to buffer your string (or create DOM objects instead, don't use += to build a string).



document.getElementById("stars").innerHTML = getStars(3.6);

function getStars(rating) {

  // Round to nearest half
  rating = Math.round(rating * 2) / 2;
  let output = [];

  // Append all the filled whole stars
  for (var i = rating; i &gt;= 1; i--)
    output.push('&lt;i class="fa fa-star" aria-hidden="true" style="color: gold;"&gt;&lt;/i&gt;&amp;nbsp;');

  // If there is a half a star, append it
  if (i == .5) output.push('&lt;i class="fa fa-star-half-o" aria-hidden="true" style="color: gold;"&gt;&lt;/i&gt;&amp;nbsp;');

  // Fill the empty stars
  for (let i = (5 - rating); i &gt;= 1; i--)
    output.push('&lt;i class="fa fa-star-o" aria-hidden="true" style="color: gold;"&gt;&lt;/i&gt;&amp;nbsp;');

  return output.join('');

}
&lt;link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /&gt;

&lt;b&gt;Rating: &lt;span id=stars&gt;&lt;/span&gt;&lt;/b&gt;