Ali Zia Ali Zia - 11 days ago 6
Javascript Question

How can I print stars in decimals

I have a function that would take parameter as whole number or decimals suppose

function printStars(n)


where n can be 1,1.25,1.5,1,75 etc upto 5.

I have different classes for stars.

<i class="icon icon-star-0 margin-right-5 size-icon-15"></i> (empty)
<i class="icon icon-star-25 margin-right-5 size-icon-15"></i> (25% filled)
<i class="icon icon-star-50 margin-right-5 size-icon-15"></i> (50% filled)
<i class="icon icon-star-75 margin-right-5 size-icon-15"></i> (75% filled)
<i class="icon icon-star-100 margin-right-5 size-icon-15"></i> (100% filled)


I want a code where if i enter the number like
printStars(3.75)
, i will give me the string

<i class="icon icon-star-100 margin-right-5 size-icon-15"></i>
<i class="icon icon-star-100 margin-right-5 size-icon-15"></i>
<i class="icon icon-star-100 margin-right-5 size-icon-15"></i>
<i class="icon icon-star-75 margin-right-5 size-icon-15"></i>


I made the code but it is not handling decimals. Can anyone guide me? This is my current code.

function printStars(n){
var str=n.toString();
var splited=str.split('.');
var a=new Array();
var html = '';
a=splited;
if (a[1]==undefined){
a[1] = '0';
}
if (a[0]>0){
var filled = Number(a[0]) + Number(1);
} else {
var filled = Number(a[0]);
}

var left = Number(5) - Number(filled);

if (a[0]>0){
for (var i = 1; i <= filled-1; i++){
if (i==1){
html += '<i class="icon icon-star-100 margin-left-5"></i>';
} else {
html += '<i class="icon icon-star-100"></i>';
}

}
html += '<i class="icon icon-star-'+a[1]+'"></i>';
for (var i = 1; i <= left; i++){
html += '<i class="icon icon-star-0"></i>';
}
} else {
for (var i = 1; i <= filled; i++){
if (i==1){
html += '<i class="icon icon-star-100 margin-left-5"></i>';
} else {
html += '<i class="icon icon-star-100"></i>';
}
}
for (var i = 1; i <= left; i++){
html += '<i class="icon icon-star-0"></i>';
}
}

return html;

console.log('filled:'+filled);
console.log('left:'+left);

}


But is does not work for numbers below 1.

Answer
function printStars(n){
    setItem('rating',n);

    var wholestars = Math.floor(n); //Round down to nearest whole
    var extrastar = (Math.round((n-wholestars) * 4) / 4).toFixed(2); //Round to nearest 0.25 (- wholestars)
    var emptystars = 5-Math.ceil(n); //Get empty stars

    var html = '';
    count = 1;

    // Whole Stars
    for (var i = 1; i <= wholestars; i++){
        html += '<i class="icon icon-star-100" onclick="fillstars('+count+')"></i>';
        count++;
    }
    // Extra Star
    if(extrastar!=0) {
        html += '<i class="icon icon-star-'+((extrastar*100).toString())+'" onclick="fillstars('+count+')"><i>';
        count++;
    }
    // Empty Stars
    for (var i = 1; i <= emptystars; i++){
        html += '<i class="icon icon-star-0" onclick="fillstars('+count+')"></i>';
        count++;
    }


    return html;
}
Comments