栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

获取Python十进制的精确十进制字符串表示形式?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

获取Python十进制的精确十进制字符串表示形式?

简短答案:

>>> dDecimal('1E-14')>>> '{:f}'.format(d)'0.00000000000001'

长答案:

正如布兰登·罗德斯(Brandon
Rhodes)
指出的,PEP
3101
(这是字符串格式PEP)指出:

格式说明符的语法是开放式的,因为类可以覆盖标准格式说明符。在这种情况下,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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/669538.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号