简短回答:
>>> d
Decimal('1E-14')
>>> '{:f}'.format(d)
'0.00000000000001'
长答案:
As 布兰登·罗兹指出PEP 3101(这是字符串格式 PEP)指出:
格式说明符的语法是开放式的,因为类可以
覆盖标准格式说明符。在这种情况下,
str.format() 方法仅传递 str.format() 之间的所有字符
第一个冒号和相关底层的匹配大括号
格式化方法。
因此,Decimal.__format__
方法是 python 的字符串格式将用来生成str
的代表Decimal
价值。基本上Decimal
覆盖格式为“智能”,但将默认为格式字符串设置的任何值(即{:.4f}
会将小数截断至 4 位)。
这就是为什么您可以信任它(摘自decimal.py:Decimal.__format__
):
def __format__(self, specifier, context=None, _localeconv=None):
#
# ...implementation snipped.
#
# figure out placement of the decimal point
leftdigits = self._exp + len(self._int)
if spec['type'] in 'eE':
if not self and precision is not None:
dotplace = 1 - precision
else:
dotplace = 1
elif spec['type'] in 'fF%':
dotplace = leftdigits
elif spec['type'] in 'gG':
if self._exp <= 0 and leftdigits > -6:
dotplace = leftdigits
else:
dotplace = 1
# find digits before and after decimal point, and get exponent
if dotplace < 0:
intpart = '0'
fracpart = '0'*(-dotplace) + self._int
elif dotplace > len(self._int):
intpart = self._int + '0'*(dotplace-len(self._int))
fracpart = ''
else:
intpart = self._int[:dotplace] or '0'
fracpart = self._int[dotplace:]
exp = leftdigits-dotplace
# done with the decimal-specific stuff; hand over the rest
# of the formatting to the _format_number function
return _format_number(self._sign, intpart, fracpart, exp, spec)
长话短说,Decimal.__format__
方法将根据提供的幂计算必要的填充来表示小数点之前和之后的数字Decimal._exp
(在您的示例中,14 位有效数字)。
>>> d._exp
-14