0

For a school project, they wanted to create a fast-food ordering program. Whenever I add something to the total that ends with zero it won't print it. For example, if I wanted it to print as '7.50' it will print '7.5'.

The section of the code I'm working with:

total = 5.75

def beverage_order():
    global total
    again = True
    while again == True:
        print('''

        Beverage size:

        1) small $1.00
        2) medium $1.75
        3) large $2.25

        ''')
        
        beverage_size = int(input('Enter the number for what beverage size you want: '))
        
        if beverage_size == 1:
            total += 1.00
            again = False
            size = 'small'
            print("You've purchased the small beverage for $1.00.")
        elif beverage_size == 2:
            total += 1.75
            again = False
            size = 'medium'
            print("You've purchased the medium beverage for $1.75.")
        elif beverage_size == 3:
            total += 2.25
            again = False
            size = 'large'
            print("You've purchased the large beverage for $1.75.")
        else:
            print('Try again')

again = True
while again == True:
    print('Would you like a beverage?')
    beverage = int(input('(1)Yes or (2)No: '))

    if beverage == 1:
        again = False
        beverage_order()
    elif beverage == 2:
        again = False
    else:
        print('Try again!')

print('Your current total: $' + str(total) + '.')

Say If I choose medium as my beverage option it will print 'Your current total: $7.5.'. Can some one help me fix this? Sorry if this is a newbie question, I am still pretty new to python.

Linkio
  • 57
  • 5

5 Answers5

3

I personally like f-strings:

print(f'Your current total: ${total:.2f}.')

https://realpython.com/python-f-strings/

nimig
  • 155
  • 1
  • 11
  • Yes, thank you! I've seen people use f-strings before, but I didn't quite understand them so this will be super useful. – Linkio May 03 '21 at 22:16
1

Use the format function:

price = 7.50
print(price)  # 7.5

formatted_price = format(price, '.2f')  # the .2f means use two decimal places
print(formatted_price)  # 7.50
Scrapper142
  • 566
  • 1
  • 3
  • 12
1

You could try using str.format.

formatted_total = "{:.2f}".format(total)

print('Your current total: $' + str(formatted_total) + '.')
0
b=50

print("%.2f"%b)
# 50.00
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
-1

You should try this with x your number and n the precision after the comma :

round(x, n)
Romain P.
  • 119
  • 1
  • 8