簡體   English   中英

如何四舍五入到小數點后4位?

[英]How to round to 4 decimal places?

我有以下代碼,我想在 Python 3 中按小數點后 4 位四舍五入。我嘗試使用 round,但一直出現語法錯誤。

fname = input("Enter a file name: ")
try:
    ffile = open(fname)
    ssum = 0
    nline = 0
    for nline, line in enumerate(ffile):
        if line.strip().startswith("X-DSPAM-Confidence:"):
            colon = line.find(":")
            slash = line.find("\\")
            current_av = line[colon+1:slash]
            ssum = ssum + float(current_av)
            print ("Average Spam confidence: ", ssum/nline)
except:
  print "This file was not found"

我試過ssum = (round(ssum, 4)) ,但小數點沒有四舍五入。

我試過 ssum = (round(ssum, 4)),但小數點沒有四舍五入。

是的,這是正確的圓角方法。 您在外部有一組額外的括號,但這不會影響調用。 你在做什么就像這個例子:

>>> import math
>>> round(math.pi, 4)
3.1416

一直收到語法錯誤。

 print "This file was not found"

那行不通,在python3中不行。 調用打印函數時使用括號:

    print("This file was not found")

暫無
暫無

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

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