[英]Converting from three decimals places to two decimal places in a list
I have a list online= [204.945, 205.953, 346.457]
and I want to only have the numbers in the list to two decimal places (one list rounded and one list not-rounded).我有一个
online= [204.945, 205.953, 346.457]
并且我只想将列表中的数字保留到小数点后两位(一个列表四舍五入,一个列表未四舍五入)。 So like this, online= [204.94, 205.95, 346.45]
for the not rounded and like this online= [204.95, 205.95, 346.46]
for the rounded.所以像这样,
online= [204.94, 205.95, 346.45]
表示未四舍五入,像这样online= [204.95, 205.95, 346.46]
表示四舍五入。
I don't even know any code that makes this possible, so I don't really have a code to show my approach.我什至不知道任何使这成为可能的代码,所以我真的没有代码来展示我的方法。 I mean I did try to play around with
int()
but that seems to remove all the decimal places and just gives me an integer.我的意思是我确实尝试过使用
int()
但这似乎删除了所有小数位,只是给了我一个 integer。
Following function will do that:以下 function 将这样做:
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)
But know, that rounding doubles does not save memory.但要知道,四舍五入不会保存 memory。 If you just want string representation of your list elements to be shorter then use:
如果您只想让列表元素的字符串表示更短,请使用:
print("{:.2f}".format(online[i]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.