2017-05-19 36 views
-1

我有一個數字15.579。我想將其格式化爲0.15790000E + 02。 我可以將它顯示爲1.57900000E + 01,但我希望小數點前有一個0。 我該怎麼用Python做到這一點?如何在Python中格式化浮點數?

+0

@ChandaKorat:這「可能重複」希望標準的科學記數法,而這一次想要一個非標準的形式,其中尾數(尾數)爲0.1和1之間。因此,這不是一個重複的 - 儘管這問題可能有其他問題。 –

+0

感謝羅裏理解這個問題。請,你能幫我解決這個問題嗎? –

+0

你想顯示多少個小數位?這將是一致的還是你想要它作爲參數?我現在需要離開,直到今天下午(從現在起7個小時)才能回答。 –

回答

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'