0

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.

Zegary
  • 13
  • 4
  • 1
    Have you tried to use the `round` function? – mkrieger1 Jun 02 '21 at 22:41
  • Does this answer your question? [Round float to 2 digits after dot in python](https://stackoverflow.com/questions/44101877/round-float-to-2-digits-after-dot-in-python) – mkrieger1 Jun 02 '21 at 22:42
  • They're both rounded, just in different directions. (One rounds down, the other towards the nearest hundredths.) – chepner Jun 02 '21 at 22:48
  • @mkrieger1 I just got introduced to round functions and that solved my problem. – Zegary Jun 02 '21 at 23:32

2 Answers2

1

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]
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
  • This worked but it seems to round the last digit. Is there a way to go from lets say `x=[5.67, 6.68]` to `y=[5.6, 6.6]` without any rounding. – Zegary Jun 02 '21 at 23:56
  • @Zegary That's called Truncation not rounding, You can take a look at [How to truncate float values?](https://stackoverflow.com/questions/783897/how-to-truncate-float-values) – ThePyGuy Jun 03 '21 at 00:07
0

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]))
user2952903
  • 365
  • 2
  • 10