使用“%”运算符时,格式化十进制对 "g" 选项的行为与 "format" 不同
Formatted Decimal has different behaviour for the "g" option when using "%" operator vs "format"
>>> "{:g}".format(Decimal('1.100'))
'1.100'
>>> "%g" % Decimal('1.100')
'1.1'
这只是 decimal 包中的一个错误,还是它有意让格式与旧的“%”运算符有不同的行为?
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
>>> "{:g}".format(Decimal('1.100'))
'1.100'
>>> "%g" % Decimal('1.100')
'1.1'
这只是 decimal 包中的一个错误,还是它有意让格式与旧的“%”运算符有不同的行为?
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