在输出中使用逗号

时间:2017-09-25 18:05:01

标签: python python-3.x

我在一个介绍编程课程中迷失了。我们有几个实验室需要知识,我们还没有被教过,但我已经设法在谷歌上找到我需要的东西(因为没有人回应课程留言板)但这个有我很沮丧。我在这里添加了一个pastebin链接:https://pastebin.com/6JBD6NNA

`principal = input()
print('Enter the Principal Value of your investment: $', float(principal))

time = input()
print('\nEnter the Time(in years) you plan to save your investment: ', int(time))

rate = input()
print('\nEnter the Rate (2% = 0.02) you will collect on your investment: ', float(rate))


interest = (float(principal) * float(rate)) * int(time)
final_value = float(principal) + float(interest)
print('\nThe Final Value of your investment will be: $%.2f' % final_value)`

所以我需要美元金额的输出有一个逗号($ 27,500.00),但我不知道如何做到这一点。我在这个网站和其他网站上看到过几个解决方案,但我无法让它们运行。请有人帮帮我吗?

3 个答案:

答案 0 :(得分:2)

在Python 2.7或更高版本中,您可以使用

print('The Final Value of your investment will be: ${:,.2f}'.format(final_value))

这在PEP 378中有记载。

来源:Python Add Comma Into Number String

答案 1 :(得分:1)

你的最后一行应该是:

print ("\nThe Final Value of your investment will be: ${:,.2f}".format(final_value))

答案 2 :(得分:1)

这是一个有效的例子:

principal = float(input('Enter the Principal Value of your investment: $'))

time = int(input('\nEnter the Time(in years) you plan to save your investment: '))

rate = float(input('\nEnter the Rate (2% = 0.02) you will collect on your investment: '))


interest = principal * rate * time
final_value = principal + interest
print('The Final Value of your investment will be: ${:,.2f}'.format(final_value))