2016-04-27 13 views
1

pythonで浮動小数点定数の桁数(小数点の前後)を保持したいと思います。 1234.56789 1234.567 しかし 12345.6789は、小数点以下の桁数があるため、この場合には動作しません修正 12345.67Pythonでの総桁数(新しい書式設定)

になるになる:私は7の固定幅を課すしたい場合例えば

、それは小数点の前に何桁の数字があるかによって決まります。私も[幅]オプションを試しましたが、最小の幅を課すため、最大値が必要です。

ありがとうございました!

+0

'("%8s "%(my_float))。strip()'? –

+0

@ JoranBeasley、 '%s'の書式設定は古い書式設定です。 '{}'は新しいスタイルです。 –

答えて

0

ちょうどあなたの例を使用することにより、

a = 1234.56789
b = 12345.6789
str(a)[:8] # gives '1234.567' 
str(b)[:8] # gives '12345.67' 
+0

それは私が必要としたものです。私はまだいくつかの数字が負になる可能性があるので問題はありましたが(そして記号は桁数に数えられません)、if文を追加してこれで十分です。ありがとう! – Fanny

0

最も簡単な解決策は、桁数よりも少ないものと指数形式を使用することが考えられます。

"{0:.6e}".format(1234.457890123) = '1.234568e+03' 

私は山車だけでなく、指数関数を印刷することができ、このソリューションを書き終わったが、それはほとんどのニーズに合わせて、おそらく不必要に長いです。

import numpy as np 

def sigprint(number,nsig): 
    """ 
    Returns a string with the given number of significant digits. 
    For numbers >= 1e5, and less than 0.001, it does exponential notation 
    This is almost what ":.3g".format(x) does, but in the case 
    of '{:.3g}'.format(2189), we want 2190 not 2.19e3. Also in the case of 
    '{:.3g}'.format(1), we want 1.00, not 1 
    """ 

    if ((abs(number) >= 1e-3) and (abs(number) < 1e5)) or number ==0: 
     place = decplace(number) - nsig + 1 
     decval = 10**place 
     outnum = np.round(np.float(number)/decval) * decval 
     ## Need to get the place again in case say 0.97 was rounded up to 1.0 
     finalplace = decplace(outnum) - nsig + 1 
     if finalplace >= 0: finalplace=0 
     fmt='.'+str(int(abs(finalplace)))+'f' 
    else: 
     stringnsig = str(int(nsig-1)) 
     fmt = '.'+stringnsig+'e' 
     outnum=number 
    wholefmt = "{0:"+fmt+"}" 

    return wholefmt.format(outnum) 

def decplace(number): 
    """ 
    Finds the decimal place of the leading digit of a number. For 0, it assumes 
    a value of 0 (the one's digit) 
    """ 
    if number == 0: 
     place = 0 
    else: 
     place = np.floor(np.log10(np.abs(number))) 
    return place 
0

あなたはまた、切り捨てしたいようですねdecimal

を使用した場合の精度を設定することができますが、必要であれば、他の丸めオプションを選択することができます。精度、丸めロジック、その他のオプションを含むコンテキストを作成します。将来のすべての操作にコンテキストを適用するには、setcontext、単一の数値をnormalize、またはlocalcontextを使用するコンテキストマネージャーを使用します。

import decimal 
ctx = decimal.Context(prec=7, rounding=decimal.ROUND_DOWN) 
print(decimal.Decimal.from_float(1234.567890123).normalize(ctx)) 
print(decimal.Decimal.from_float(12345.6789).normalize(ctx)) 
関連する問題