【问题标题】:Twig for loop problem : stars rating systemTwig for loop 问题:星级评分系统
【发布时间】:2022-01-18 21:41:54
【问题描述】:

我正在尝试为电影生成星级评分系统,但不知何故,如果评分 >= 2,我的算法将不起作用,值如 2.2、2.8、3.2 等...不会输出正确的星级.

<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

【问题讨论】:

    标签: algorithm for-loop twig


    【解决方案1】:

    浮点数的精度有限,应避免比较它们。
    Comparing floats - same number, but does not equal? 阅读更多信息

    要解决您的问题,请将 EPSILON 添加到您的比较中 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>
    

    这应该可行。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-02
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多