General formatting在 Python 中将数字四舍五入为 p如果指数为 %f,则为有效数字并打印为 float (exp)介于 -4 <= exp < p 之间, 否则它以科学指数表示法 ( %e ) 打印。例如:
> '{0:0.8G}'.format(10000000)
'10000000'
> '{0:0.8G}'.format(0.000001)
'1E-06'
为什么这个条件只能指定指数上限精度,而指数下限固定为-4?有什么方法可以强制字符串格式打印低指数的完整数字吗?
请您参考如下方法:
Is there any way of forcing string formatting to print the full number for low exponents?
没有办法强制 G 始终使用定点表示法进行格式化,但您可以使用具有自定义精度的 f 和 .rstrip():
>>> '{:.10f}'.format(0.0000000001)
'0.0000000001'
>>> '{:.10f}'.format(0.00001).rstrip('0') # remove trailing zeros
'0.00001'
>>> '{:.10f}'.format(1000).rstrip('0').rstrip('.') # remove trailing zeros and '.'
'1000'
