【问题标题】:converting and multiply float to int in django templates在 Django 模板中将浮点数转换并乘以 int
【发布时间】:2020-04-18 02:31:01
【问题描述】:

我正在从股票 API 中获取一些数据并获得一些值(作为浮点数存储在数据库中) 如下:

YTD Change 0.379996
daily % change 0.00854

我的看法如下:

def get_stock(request):
    empty = True
    localStocks = Stock.objects.all()
    if len(localStocks) > 0 :
        empty = False

    return render (request,'get_stock.html',{'empty':empty, 'output':list(localStocks)})

还有我的模板

<section class="section-typography container u-readable">
      <table>
        <thead>
          <tr>
            <th>Ticker</th>
            <th>Name</th>
            <th>Price</th>
            <th>Last Time</th>
            <th>% Change</th>
            <th>52W High</th>
            <th>52W Low</th>
            <th>YTD Change</th>
          </tr>
        </thead>
        <tbody>

            {% if not empty %}
              {% for list_item in output %}
                  <tr>
                    <td>  {{list_item.symbol  }}</td>
                    <td>  {{ list_item.companyName }}</td>
                    <td>  {{ list_item.latestPrice }}</td>
                    <td>  {{ list_item.latestTime }}</td>
                    <td>  {{ list_item.changePercent }}</td>
                    <td>  {{ list_item.week52High }}</td>
                    <td>  {{ list_item.week52Low}}</td>
                    <td>   {{  list_item.ytdChange }}</td>
                  </tr>
              {% endfor %}
          {% endif %}
        </tbody>
      </table>
    </section>    
{% endblock %}

股票年初至今的百分比变化不是 0.379996,而是 37.99%,这就是我想要显示的。同样,每日变化不是 0.00854 而是 0.85% 。如何在视图或模板上操作日期以基本上将其相乘并仅显示浮点数的前 2 位小数?

【问题讨论】:

标签: python django python-3.x


【解决方案1】:

您需要实现自定义模板标签。在你的 app 目录中创建一个名为 templatetags 的新模块。在这个模块里面应该有一个空白的__init__.py 和一个随机命名的文件,比如percentage.py

您的percentage.py 应包含:

#percentage.py

from django import template

register = template.Library()

@register.simple_tag(name="percentage")
def percentage(value):
    return str(round(value *100,2))+'%'

在任何要使用此标签的 html 文件中,您应该在文件开头使用{% load percentage %} 加载此标签。为了将所需的值传递给模板标签,您需要像这样使用它:{% percentage list_item.changePercent %}

【讨论】:

    【解决方案2】:

    最好的方法是更改​​视图中的值,如下所示: YTD_to_pass = ((YTD*10000)//1/100) 这会将值乘以 100 并在整数后保留 2 位数字 然后只需在模板中添加一个 % 符号。

    【讨论】:

      猜你喜欢
      • 2012-11-04
      • 2023-03-21
      • 2018-06-20
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多