【问题标题】:Round a float to an int within jinja2将浮点数舍入到 jinja2 中的 int
【发布时间】:2019-07-24 02:09:39
【问题描述】:

我正在尝试在我的应用程序中创建评分(星)用户界面。我所有的“收视率”都是float。我想将该评级四舍五入以使其成为整数并显示那么多星。我似乎无法弄清楚如何让 jinja 喜欢它。

示例评分:3.02.35.04.6 等...

失败,因为TypeError: 'float' object cannot be interpreted as an integer

{% if book.average_score %}
  {% for s in range(book.average_score) %}
     <i class="fas fa-star"></i>
  {% endfor %}
{% endif %}

我以为我可以使用math

{% if book.average_score %}
  {% for s in range(math.ceil(book.average_score)) %}
     <i class="fas fa-star"></i>
  {% endfor %}
{% endif %}

但是,这会导致jinja2.exceptions.UndefinedError: 'math' is undefined。我假设这是因为我正在使用 Flask 并且模板不知道 math 库。

然后我在玩round

{% if book.average_score %}
  {% for s in range(round(book.average_score)) %}
     <i class="fas fa-star"></i>
  {% endfor %}
{% endif %}

但后来我得到了jinja2.exceptions.UndefinedError: 'round' is undefined

我在the round documentation 之后使用round 做了更多变体,但没有成功。我知道在 Angular 中,你有 pipes 对这类事情真的很有帮助。 jinja 有类似的东西吗?还是我在这里离题了?

This SOF 线程似乎是我能找到的最接近我要解决的问题的东西。然而,似乎并没有让我走得更远。

【问题讨论】:

    标签: flask jinja2


    【解决方案1】:

    您正在使用 Jinja,但您已链接到 Python 函数文档。 Jinja != Python:使用 Jinja 表达式时,您需要使用 filters 或对象方法。因此,例如,您可以使用int 过滤器:

    {% if book.average_score %}
      {% for s in range(book.average_score|int) %}
         <i class="fas fa-star"></i>
      {% endfor %}
    {% endif %}
    

    round 过滤器:

    {% if book.average_score %}
      {% for s in range(book.average_score|round) %}
         <i class="fas fa-star"></i>
      {% endfor %}
    {% endif %}
    

    您可以使用method 参数控制round 过滤器的行为,该参数可以是common(默认值)、floorceil

    {% if book.average_score %}
      {% for s in range(book.average_score|round(method='ceil')) %}
         <i class="fas fa-star"></i>
      {% endfor %}
    {% endif %}
    

    更新

    看起来自从写了这篇文章以来,round 过滤器可能已经改变了。查看the documentationmode 参数不存在,但有method 参数。以下工作:

    • 指定精度和方法;不需要关键字参数:

      >>> t = jinja2.Template("Value: {{ value|round(2, 'ceil') }}")
      >>> print(t.render(value=4.1234))
      Value: 4.13
      
    • 只指定一个舍入方法;使用method 关键字:

      >>> t = jinja2.Template("Value: {{ value|round(method='ceil') }}")
      >>> print(t.render(value=4.1234))
      Value: 5.0
      

    我已更新答案的原始部分以反映此更改。

    【讨论】:

    • 所以这对十进制类型不起作用..必须使用它 - stackoverflow.com/a/48727177/2048229
    • ...|int) 对于十进制类型(来自 sqlite 表的浮点类型)对我来说工作得很好,结果我在 jinja 呈现的模板中得到了 int
    • TypeError: do_round() got an unexpected keyword argument 'mode'
    • @HarshaBiyani 谢谢,看起来语法可能已经改变了。我已经更新了答案以包含适用于当前版本的示例。
    猜你喜欢
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 2010-10-28
    • 2016-05-09
    • 2012-11-08
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    相关资源
    最近更新 更多