![](/img/trans.png)
[英]Number to string conversion with f-string without leading or trailing zeros?
[英]Display trailing zeros in a decimal number in python without returning a string
我需要在十進制數字中顯示尾隨零 。 我考慮過使用python format(),但它返回一個字符串 ,當我將其轉換為float或十進制時 , 尾隨零消失 s。
我也嘗試使用python十進制,但是它在變量賦值時返回Decimal實例 。 例如:
>>> x = decimal.Decimal(format(15.2, '.2f'))
>>> print x
15.20
>>> x
Decimal('15.20')
Python版本:2.7
我需要將15.2顯示為15.20(而不是顯示為'15 .20'<<字符串類型)
提前致謝
您可以創建一個行為如下的float
子類:
class RoundFloat(float):
def __new__(cls, value=0, places=2):
return float.__new__(cls, value)
def __init__(self, value=0, places=2):
self.places = str(places)
def __str__(self):
return ("%." + self.places + "f") % self
__repr__ = __str__
用法:
pi = RoundFloat(3.1415927, places=4)
print pi # 3.1416
__repr__
可能很方便,因此如果需要,可以使用repr(x)
輕松獲得完整值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.