Round Decimal

Asked

Viewed 133 times

3

Dear gentlemen I’m doubtful of rounding in python.

I know, for example, that if I have a variable like this,:

n=2.23445
print (f'o valor de n é {n:.2f})

will print 2.23

But in the case of a list?

lista [2.23453, 2.34543, 2.457755]

How do I round the list items?

3 answers

2

You can use list comprehension. In this case the answer would be...

lista = [2.23453, 2.34543, 2.457755]
lista_1 = [round(item, 2) for item in lista]
print(lista_1)

In this case, the items on the list have been rounded off with duas casas decimais.

1

To print the rounded elements just put the vector name and the element index.

For example:

lista = [2.23453, 2.34543, 2.457755]

print (f'O valor do elemento de índice 0 da lista é: {lista[0]:.2f}')

To print all the values of the rounded list we can use the for loop:

for x in range(len(lista)):
    print(f'o valor do elemento de índice {x} é {lista[x]:.2f}')

1

Depends on what you mean by "round off the list items".

If you want only print the rounded values, make a loop by the elements and prints them:

for n in lista:
    print(f'{n:.2f}')

In that case, as the idea is only print, you wouldn’t need to create another list, as suggested in another answer (it would only make sense to create another list if you were to use it for other things later, otherwise you would be creating it for nothing).

Of course you can do some "twitches":

for i, n in enumerate(lista, start=1):
    print(f'{i}º elemento = {n:.2f}')

Printing:

1º elemento = 2.23
2º elemento = 2.35
3º elemento = 2.46

But anyway, once you go through the list, you can do whatever you want with each element.


But if "round off the list items" means to create another list with rounded values, then you can do:

rounded = [ round(n, 2) for n in lista ]

I used round instead of f-string, because if I do f'{n:.2f}' the result will be a string. But if you want a list of numbers, you must use round. Of course, printing won’t make a difference because the values will be displayed the same way, but if you’re going to use this list for something later (like making calculations), you’d better create it with numbers instead of strings.

Remembering that in this case, as the numbers have already been rounded, just print them directly:

for n in rounded:
    print(n)

Finally (although not the focus of the question), read the documentation on floating point number limitations, to understand, among other things, why round(2.675, 2) is 2.67 and not 2.68.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.