Formatting two decimal places using list (Python)

0

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

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

Follow 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}')
    
asked by anonymous 26.01.2018 / 17:33

1 answer

3

As you may have noticed, it is best to keep numbers as numbers while the program is running - and only bother to format the presentation when it is or print the result, or save it in a text file, (page html, etc ...).

Trying to round the number to two decimal places with round is innocuous: the internal representation of the floating-point number in base 2 is generally not compatible with the decimal base - and the number returns to a "bundle" . In production applications that deal with monetary values, the practice is to either always use integers, and divide by 100 at the time of presenting it to the user, or use the decimal.Decimal class of Python that uses an internal representation in decimal and a configurable number of houses after the decimal point

For applications where the number is not critical and we can use the float data type, by the time the number becomes string for display, you can either use the format method of strings as you are using, or the new Python 3.6 f-strings - in your case you made almost correct use, but there was a code for Python to fill in the boxes to the number you want even if you do not need it.

Instead of:

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

Use:

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

Note the "0" more inside the formatting string.

Similarly, in the above line, you just have to use the f-strings feature to print the numbers. Instead of:

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

You 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 : to put the formatting specifications - in case: floating point, with two houses after the decimal point, filling with 0. The possible formatting after the ":" in a field is quite flexible, and its documentation is the same as for the .format strings method - here: link

For those of you using an old version of Python as 3.5 or (three beats on wood) 2.7, you can use the .format :

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

A detail not directly related to your answer, but important - it is not legal to use lists to store structured information - that is: the product name at index 0 and its price at index 1. Nothing prevents, but since we have dictionaries and namedtuples that allow you to do the same thing, but you can see what each field means, that's better.

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

    
26.01.2018 / 18:04