2011-02-10 70 views
0

我想在模板中以百分比表示十進制值。具體來說,我在模型中有幾個字段,其值爲'0.4000000059604645'。在models.py我把它作爲representated在Django視圖中的乘法

information_percent = models.FloatField(blank=True) 

而且在視圖中我有:

org = Organizationaldata.objects.get(name=organization) 
    information_percent = org.information_percent 

我無法弄清楚是如何獲得,例如,'40 0.0' 這顯示爲,在模板中。我做了大量的搜索,並且我無法弄清楚如何將值乘以100,或者其他一些可以提供預期結果的技術。

建議將不勝感激。

回答

2

聽起來像是你需要的built-in floatformat template filter

例如:

views.py

org = Organizationaldata.objects.get(name=organization) 
information_percent = 100 * org.information_percent 

template.html

<span>Info percent: {{ information_percent|floatformat:1 }}</span> 
1

也許這就是你想要的?

information_percent = int(org.information_percent*100) 

如果你想在小數部分,你可以把它擴展到:

information_percent = int(org.information_percent*100) + (org.information_percent*100 - int(org.information_percent*100)) 
+0

感謝。這工作,但會使'16 .654'爲'16'。對於其他意見,這可能適合我,所以我很欣賞答案。 – 2011-02-10 04:18:28

+0

沒問題。正如你所說,它只適用於範圍[0,1]範圍內的數字並且想將它們轉換爲百分比... – Piva 2011-02-10 04:26:40