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
reviewStarRatingwould == 100% - 4.0
reviewStarRatingwould == 80% - 3.0
reviewStarRatingwould == 60% - 2.0
reviewStarRatingwould == 40% - 1.0
reviewStarRatingwould == 20% - 0.0
reviewStarRatingwould == 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 = '★';
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;
}