我已经在 Python2、Python3 和 C 中尝试过这个:
为什么这些格式字符串返回的数字精度不同?
>>> "%.3e" % 123456789
'1.235e+08'
>>> "%.3g" % 123456789
'1.23e+08'
最佳答案
'e'
:Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent. The default precision is
6
.
'g'
:General format. For a given precision
p >= 1
, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.The precise rules are as follows: suppose that the result formatted with presentation type
'e'
and precisionp-1
would have exponentexp
. Then if-4 <= exp < p
, the number is formatted with presentation type'f'
and precisionp-1-exp
. Otherwise, the number is formatted with presentation type'e'
and precisionp-1
. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the'#'
option is used.Positive and negative infinity, positive and negative zero, and nans, are formatted as
inf
,-inf
,0
,-0
andnan
respectively, regardless of the precision.A precision of
0
is treated as equivalent to a precision of1
. The default precision is6
.
具有替代值:
>>> "%.3e" % 123
'1.230e+02'
>>> "%.3g" % 123
'123'
>>> "%.3e" % 1234
'1.234e+03'
>>> "%.3g" % 1234
'1.23e+03'
区别显然在于如何指定精度。 g
似乎使用精度作为精度的正常定义,而 e
使用小数点后 的位数。
关于python - 为什么 %e 在格式字符串中的行为与 %g 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30580481/