将列表中的三位小数转换为两位小数

Converting from three decimals places to two decimal places in a list

我有一个列表 online= [204.945, 205.953, 346.457],我只想将列表中的数字保留到小数点后两位(一个列表四舍五入,一个列表不四舍五入)。所以像这样,online= [204.94, 205.95, 346.45] 表示不圆整,像这样 online= [204.95, 205.95, 346.46] 表示圆整。

我什至不知道任何使这成为可能的代码,所以我真的没有代码来展示我的方法。我的意思是我确实尝试过 int() 但这似乎删除了所有小数位并只给了我一个整数。

您可以使用round() along with map() and lambda

list(map(lambda x: round(x,2), online))

或者,List-Comprehension

[round(item,2) for item in online]

输出:

[204.94, 205.95, 346.46]

以下函数将执行此操作:

def to_2_decimals(l):
    for i in range(len(l)):
        l[i]=int(l[i]*100)/100

online= [204.945, 205.953, 346.457,0.0147932132,142314324.342545]
to_2_decimals(online)
print(online)

但是要知道,四舍五入不会节省内存。如果您只想缩短列表元素的字符串表示形式,请使用:

print("{:.2f}".format(online[i]))