Zegary
Zegary

Reputation: 3

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). 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.

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.

Upvotes: 0

Views: 484

Answers (2)

user2952903
user2952903

Reputation: 385

Following function will do that:

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. If you just want string representation of your list elements to be shorter then use:

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

Upvotes: 0

ThePyGuy
ThePyGuy

Reputation: 18416

You can use round() along with map() and lambda

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

Or, List-Comprehension

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

OUTPUT:

[204.94, 205.95, 346.46]

Upvotes: 1

Related Questions