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