当使用“%”运算符与“format”运算符时,“g”选项的格式化十进制具有不同的行为

2024-04-25 14:34:55 发布

您现在位置:Python中文网/ 问答频道 /正文

>>> "{:g}".format(Decimal('1.100'))
'1.100'
>>> "%g" % Decimal('1.100')
'1.1'

这仅仅是decimal包中的一个bug,还是它的目的是使格式具有与旧的“%”运算符不同的行为


Tags: 目的format格式运算符bugdecimal
1条回答
网友
1楼 · 发布于 2024-04-25 14:34:55

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(float(Decimal('1.100')))给出1.1

相关问题 更多 >

    热门问题