簡體   English   中英

如何在python中強加總位數(新格式)

[英]How can I impose the total number of digits in python (new formatting)

我想在python中保持float常量的總位數(小數點前后)。

例如,如果我想強加固定寬度7:1234.567890123將變為1234.567但12345.678901234將變為12345.67

在這種情況下,修復小數位數不起作用,因為它取決於我在小數點之前有多少位數。 我也嘗試了[width]選項,但它施加了最小寬度,我需要一個最大值。

感謝您的輸入!

只是用你的例子,

a = 1234.567890123 
b = 12345.678901234
str(a)[:8] # gives '1234.567'
str(b)[:8] # gives '12345.67'

最簡單的解決方案可能是使用指數格式,其中一個小於位數。

"{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

您可以在使用小數時設置精度

聽起來你也想要向下舍入,但如果你願意,可以選擇其他的舍入選項。 您可以創建包含精度,舍入邏輯和一些其他選項的上下文。 您可以使用setcontext將上下文應用於所有將來的操作,使用normalize將單個數字localcontext使用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.678901234).normalize(ctx))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM