Convert a decimal rating (max of 5 w/ 0.1 increments) to a percentage

Viewed 505

I'm working on a star rating system and I need to convert my decimal values to a percentage % so I can use that as a width of the top layer.

The way this works is that both span's are on top of each other. The top is colored grey, the bottom is colored orange. The closer the bottom span gets to 100% width (85px), the more "full" the stars look.

It all works as expected but now I need to convert my incoming reviewStarRating number to a percentage. The values of reviewStarRating can be 0 - 5 with 0.01 increments. So some examples of incoming reviewStarRating would be (0.4, 1.3, 2.8, 3.0, 4.2, 4.9, 5.0).

  • 5.0 reviewStarRating would == 100%
  • 4.0 reviewStarRating would == 80%
  • 3.0 reviewStarRating would == 60%
  • 2.0 reviewStarRating would == 40%
  • 1.0 reviewStarRating would == 20%
  • 0.0 reviewStarRating would == 0%

HTML

<div class="star-container">
    <span class="star-icon grey" [innerHTML]="icons"></span>
    <span class="star-icon orange" [ngStyle]="getCssWidth()" [innerHTML]="icons"></span>
</div>

JS / Angular Typescript

@Input() reviewCount: String;
@Input() reviewStarRating: String;
cssWidth: number = 0;
icon = '&#9733;';
icons = `${this.icon}${this.icon}${this.icon}${this.icon}${this.icon}`

constructor() { }

ngOnInit() {
  this.calculateCssWidth();
}
public getCssWidth() {
  let styles = {
    'width': `${this.cssWidth.toString()}px`
  }
  return styles;
}
calculateCssWidth() {
  this.cssWidth = this.round(this.reviewStarRating);
  console.log(`${this.reviewStarRating} -> ${this.cssWidth}`);
}
round(num) {
  return Math.ceil((num+1)/10)*10;
}

CSS

.star-container {
     max-width: 140px;
     width: 85px;
     height: 20px;
     line-height: 20px;
}
 .star-container .star-icon {
     font-size: 20px;
     position: relative;
}
 .star-container .star-icon.orange {
     color: #f37a1f;
     top: -22px;
     display: block;
     overflow: hidden;
}
 .star-container .star-icon.grey {
     color: #e3e3e3;
}
.star-container:not(:last-child) {
  margin-right: 5px;
}
 
2 Answers
function toPercentage(num: number) : string {
    return `${num / 5 * 100}%`;
}

Thanks to @Yosef for helping me get most of the way there. This was the solution I was looking for. The 85 is because the width of the div I was working in was 85px wide. So if i put in a 5.0 number, i wanted 85px to be the max it would return.

toPercentage(num) {
   return (num / 5 * 85);
} 
Related