2024-04-25 14:34:55 发布
网友
>>> "{:g}".format(Decimal('1.100')) '1.100' >>> "%g" % Decimal('1.100') '1.1'
这仅仅是decimal包中的一个bug,还是它的目的是使格式具有与旧的“%”运算符不同的行为
从https://pyformat.info/:
The new-style simple formatter calls by default the __format__() method of an object for its representation. If you just want to render the output of str(...) or repr(...) you can use the !s or !r conversion flags.
因此"{:g}".format(Decimal('1.100'))首先处理十进制内容上的__format__(),而另一个可能在格式化之前首先转换为浮点
"{:g}".format(Decimal('1.100'))
__format__()
"{:g}".format(float(Decimal('1.100')))给出1.1
"{:g}".format(float(Decimal('1.100')))
1.1
从https://pyformat.info/:
因此
"{:g}".format(Decimal('1.100'))
首先处理十进制内容上的__format__()
,而另一个可能在格式化之前首先转换为浮点"{:g}".format(float(Decimal('1.100')))
给出1.1
相关问题 更多 >
编程相关推荐