有问题打印总计只有两个小数点[Python 2.7]

时间:2015-03-05 23:57:36

标签: python floating-point decimal

尽管十进制格式正确,但我的计算似乎显示为不正确。

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!')   

3 个答案:

答案 0 :(得分:4)

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'

如果要添加两个数字,则需要用于旧样式格式的parens:

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 )

答案 1 :(得分:2)

total_cost = 1234.56789
print('Your total amount due is ${0:.2f}'.format(total_cost))

Your total amount due is $1234.57

答案 2 :(得分:1)

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

应该这样做