在一个函数中的浮点数四舍五入

2024-05-15 12:08:09 发布

您现在位置:Python中文网/ 问答频道 /正文

以下功能不工作:

def myround(sfloat, dec):
    print("{0:."+str(dec)+"f}")    # only to show the string formed.
    return ("{0:."+str(dec)+"f}".format(sfloat))

myround(2.35698, 2)

错误是:

{:.2f}
Traceback (most recent call last):
  File "mytest.py", line 8, in <module>
    myround(2.35698, 2)
  File "mytest.py", line 6, in myround
    return ("{0:."+str(dec)+"f}".format(sfloat))
ValueError: Single '}' encountered in format string

第一个print函数显示正确的字符串:{:.2f}。我试过{0:.2f},但也没用\{\}也不起作用

问题出在哪里,如何解决


Tags: inpy功能formatstringreturndefline