1

I'm trying to generate a stars rating system for movies, but somehow, my algorithm doesn't work if the rating >= 2, values like 2.2, 2.8, 3.2 etc... won't output the right star.

<div class="d-flex" style="color: orange;">
{% for i in range(0, 4) %}
    {% if movie.rating - i >= 0.8 %}
        <i class="bi bi-star-fill"></i>
    {% elseif movie.rating - i <= 0.2 %}
        <i class="bi bi-star"></i>
    {% else %}
        <i class="bi bi-star-half"></i>
    {% endif %}
{% endfor %}
    <span class="ps-1">{{movie.rating}}</span>
</div>

Output

Tristan
  • 35
  • 6

1 Answers1

1

Floating-point numbers have limited precision, you should avoid comparing them.
read more at Comparing floats - same number, but does not equal?

To solve your problem add a EPSILON to your comparison EPSILON=0.0000000001

<div class="d-flex" style="color: orange;">
{% for i in range(0, 4) %}
    {% if movie.rating - i + 0.0000000001 >= 0.8 %}
        <i class="bi bi-star-fill"></i>
    {% elseif movie.rating - i - 0.0000000001 <= 0.2 %}
        <i class="bi bi-star"></i>
    {% else %}
        <i class="bi bi-star-half"></i>
    {% endif %}
{% endfor %}
    <span class="ps-1">{{movie.rating}}</span>
</div>

This should works.