如何舍入到小数点后四位?

时间:2019-03-03 12:15:39

标签: python python-3.x rounding

我有以下代码,我想在Python 3中四舍五入到小数点后四位。我尝试使用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)),但是小数点后的数字未四舍五入。

1 个答案:

答案 0 :(得分:1)

  

我尝试了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")