Formatting two decimal places using list (Python)

Asked

Viewed 8,329 times

0

I have a question about the formatting of decimal digits using two houses, for example "2.00", I did this exercise but I have a little problem that I can not solve as I do not know if there is a way to do it. Format values of products that are within a list.

Example: Pen - 2.00 But the output is: Pen - 2.0

Follows the code:

fatura = []
total = 0
valid_preco = False

while True:
    produto = str(input('Produto: '))

    while valid_preco == False:
        preco = (input('Preço: '))
        try:
            preco = float(preco)
            if preco <= 0:
                print('O preço precisa ser maior que 0')
            else:
                valid_preco = True

        except:
            print("Formato inválido, utilize apenas '.'")

    fatura.append([produto, preco])     #Adiciona produto e preço à lista
    total += preco

    valid_preco = False

    sair = ' '
    while sair not in 'SN':
        sair = str(input('Deseja sair? [S/N]: ')).upper().strip()[0]

    if sair == 'S':
        break

for i in fatura:
    print(i[0], '-', i[1])      #Imprime o produto, na frente, preço.

print(f'O total da fatura é: {total:.2f}')

1 answer

3


As you may have noticed, the ideal is to keep the numbers as numbers while the program is running - and only worry about formatting the presentation when it is or printing the result, or saving it in a text file, or including it with text in some other output (html page, etc...).

Attempt to round off the number to two decimal places with the round is innocuous: the internal representation of the floating point number in the base 2 is generally not compatible with the decimal base - and the number returns to having a few "bits". In production applications that will handle monetary values, the practice is either to always use whole numbers, and divide by 100 when presenting it to the user, or to use the class decimal.Decimal Python using an internal decimal representation and a configurable number of places after the decimal point

For applications where the number is not critical and we can use the data type float, the moment the number becomes string for presentation, you can or use the method format of the strings as you are using, or the new Python f-strings 3.6 - in your case you made an almost correct use, but lacked an indicator for Python to fill the boxes up to the desired number even if you do not need.

Instead of:

print(f'O total da fatura é: {total:.2f}')

Use:

print(f'O total da fatura é: {total:.02f}')

Note the extra "0" inside the format string.

Similarly, in the line above, just use the f-string resource to print the numbers. Instead of:

print(i[0], '-', i[1]) 

Can use:

print(f'{i[0]} - {i[1]:.02f}')

Instead of printing the separate variables, a single f-string that formats the product name i[0] and its price - and with the price, we use the : to put the formatting specifications - in the case: floating point, with two boxes after decimal point, filling with 0. The possible formatting after ":" in a field is quite flexible, and its documentation is the same as for the method .format string - is here: https://docs.python.org/3/library/string.html#format-string-syntax

For those using an older version of Python such as 3.5 or (three wood beats) 2.7, the method can be used .format :

print('{0} - {1:.02f}'.format(i[0], i[1]))

A detail not directly related to your answer, but important - it’s not cool to use lists to store structured information - that is: the name of the product in index 0 and its price in index 1. Nothing prevents, but since we have dictionaries and namedtuples that allow us to do the same thing, only being able to see what each field means, this is better.

So, your information about each product could be in a dictionary, where it is easy for anyone looking at your code to know what i["product"] and i["price"] instead of i[0] and i[1].

  • Thank you very much man! Your explanation was very clean and enlightening. I didn’t really notice how to use the format in the list print and I got a little lost

  • Expand a little bit now - see from the beginning again.

  • Thanks for the jsbueno tips! Really became much more readable and easy to understand in this way, I will put into practice all the tips you passed. Thanks again, clarified more than my teacher hahaha

Browser other questions tagged

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