Возникли проблемы с распечаткой итогов только с двумя десятичными точками [Python 2.7]

Мои расчеты кажутся неверными, несмотря на то, что десятичный формат правильный.

import time # It was reccommend in our text to always have your import data located outside of any loops, thus I put mine here.

while True: # This is the main, and only; while loop.  It will repeat the program and allow users to book more reservations depending on input.
    user_people = int(raw_input("Welcome to Ramirez Airlines!  How many people will be flying?"))
    user_seating = str(raw_input("Perfect!  Now what type of seating would your party prefer? We offer Economy, Business and First Class!"))
    
    else:
        before_discount = luggage_total + seats_total
        discount_amount = before_discount * discount_rate
        after_discount = before_discount - discount_amount

        print ('Unfortunately we were not able to discount this particular transaction, however you can learn how to save 10% on future flights through our Frequent Flyers program! Contact us for more info!')
        print ('The total tax amount for your order is: $%.2f') % (before_discount * tax_rate)
        print ('Your total amount due including taxes for your airfare is: $%.2f') % (before_discount * tax_rate + before_discount)

    
    user_continue = raw_input("Your reservation was submitted successfully.  Would you like to do another?")    
    if user_continue != 'yes':
        break

print('Thank you for flying with Ramirez Airlines!')   


person Lukon    schedule 05.03.2015    source источник


Ответы (2)


print 'Your total amount due is ${:.2f}'.format(totalCost)

А также:

print 'Your total amount due is $%.2f' % totalCost 

оба печатают до двух знаков после запятой.

In [3]: 'Your total amount due is $%.2f' % 1.2234
Out[3]: 'Your total amount due is $1.22'



In [4]: 'Your total amount due is ${:.2f}'.format(1.2234)
Out[4]: 'Your total amount due is $1.22'

Если вы добавляете два числа, вам нужны скобки для форматирования в старом стиле:

In [6]: 'Your total amount due is $%.2f' % (1.2234 + 1.2324)
Out[6]: 'Your total amount due is $2.46'
In [7]: 'Your total amount due is ${:.2f}'.format(1.2234+   1.2324)
Out[8]: 'Your total amount due is $2.46'

Используя пример из вашего кода:

print ('Your total amount due including taxes for your airfare is: ${:.2f}'.format(tax_amount + after_tax )
person Padraic Cunningham    schedule 06.03.2015
comment
Падраик, спасибо за помощь! Мне удалось заставить большинство моих выходных данных отображаться как два десятичных знака, но что, если мне нужно добавить две «переменные»? Например, напечатайте («Ваша промежуточная сумма для ваших мест и багажа: $»), Baggage_total + seat_total) - person Lukon; 06.03.2015
comment
Не беспокойтесь, просто сделайте (var1 + var2) как в последнем примере. Я предпочитаю использовать str.format, так как думаю, что он менее подвержен ошибкам. - person Padraic Cunningham; 06.03.2015
comment
То же самое для такого кода: до_скидки * налоговая_ставка + до_скидки - person Lukon; 06.03.2015
comment
Да просто заключить все в скобки (before_discount * tax_rate + before_discount) - person Padraic Cunningham; 06.03.2015
comment
Хм. Итак, мне удалось заставить все отображаться в виде десятичных знаков, но по какой-то причине мои расчеты теперь отображаются как неправильные при расчете налога, скидки и т. д. Я отредактировал свой основной код, чтобы показать свою программу. не могли бы вы быстро взглянуть на это, чтобы увидеть, видите ли вы какую-либо явно очевидную проблему? - person Lukon; 06.03.2015
comment
Без проблем. я быстро посмотрю - person Padraic Cunningham; 06.03.2015
comment
Я только что сохранил свое редактирование — вы можете обновить его! Большое спасибо. - person Lukon; 06.03.2015
comment
Давайте продолжим обсуждение в чате. - person Lukon; 06.03.2015

print ('text'),("%.2f" % variable)

должен сделать это

person Esteban    schedule 06.03.2015
comment
.format() обычно считается более «питоновским», чем печать в стиле %s: stackoverflow.com/questions/14753844/ - person Alexander; 07.03.2015