我的号码是15.579。我想格式化它写0.15790000E + 02。 我可以将它显示为1.57900000E + 01,但我想要小数点前的0。 我怎么能用Python做到这一点?
答案 0 :(得分:1)
这应该有效。这会检查负数和任何奇怪的结果。我还使用了Python的默认精度,并使得小数点字符可以更改。如果您想要8个数字,可以轻松更改默认精度,如您的示例所示,但Python的默认值为6。
def alt_sci_notation(x, prec=6, decpt='.'):
"""Return a string of a floating point number formatted in
alternate scientific notation. The significand (mantissa) is to be
between 0.1 and 1, not including 1--i.e. the decimal point is
before the first digit. The number of digits after the decimal
point, which is also the number of significant digits, is 6 by
default and must be a positive integer. The decimal point character
can also be changed.
"""
# Get regular scientific notation with the new exponent
s = '{0:.{p}E}'.format(10 * x, p=prec-1)
# Handle negative values
prefix = ''
if s[0] == '-':
prefix = s[0]
s = s[1:]
# Return the string after moving the decimal point
if prec > 1: # if a decimal point exists in thesignificand
return prefix + '0' + decpt + s[0] + s[2:]
else: # no decimal point, just one digit in the significand
return prefix + '0' + decpt + s
以下是iPython中的示例结果。
alt_sci_notation(15.579, 8)
Out[2]: '0.15579000E+02'
alt_sci_notation(-15.579, 8)
Out[3]: '-0.15579000E+02'
alt_sci_notation(0)
Out[4]: '0.000000E+00'
alt_sci_notation(100000000)
Out[5]: '0.100000E+09'
alt_sci_notation(.00000001)
Out[6]: '0.100000E-07'