我正在为我的Python类做一个作业。我几乎弄明白了,但我的输出与原始问题中的显示略有不同。当利率为5.125%时,我的每月付款为189.29,但问题的输出为188.28。没有格式的原始号码是189.286。我想也许在金融系统中,他们只是简单地减少小数而不是使用“圆形”。我不确定在Python中是否有任何方法可以做到这一点。这是问题所在。
编写一个程序,让用户以年数输入贷款金额和贷款期限,并显示每个利率的月付款和总付款,从5%到8%,增量为1/8。
输入:
Loan Amount: 10000
Number of Years: 5
输出:
Interest Rate Monthly Payment Total Payment
5.000% 188.71 11322.74
5.125% 189.29 11357.13
...
7.875% 202.17 12129.97
8.000% 202.76 12165.84
代码:
LoanAmount = float(input("Loan Amount:"))
NumOfYears = float(input("Number of Years:"))
AnnualRate = float(5.0)
print("\nInterest Rate\t" + "Monthly Payment\t" + "Total Payment")
while (AnnualRate <= 8.0):
MonthlyRate = float(AnnualRate/1200)
MonthlyPayment = float(LoanAmount * MonthlyRate / (1- 1/ pow(1+MonthlyRate, NumOfYears *12)))
TotalPayment = format(MonthlyPayment * NumOfYears * 12, ".2f")
print (format(AnnualRate, ".3f"), end = "%\t\t")
print (format(MonthlyPayment, ".2f"), end = "\t\t")
print(TotalPayment, end = "\n")
AnnualRate += 1.0/8
答案 0 :(得分:5)
当您使用资金时,请使用decimal模块。这允许许多不同的rounding modes。例如,向下舍入:
import decimal
payment = decimal.Decimal('189.286')
with decimal.localcontext() as ctx:
ctx.rounding = decimal.ROUND_DOWN
print(round(payment, 2))
打印:
189.28
decimal.ROUND_HALF_EVEN
舍入到最接近的关系到最接近的偶数。
with decimal.localcontext() as ctx:
ctx.rounding = decimal.ROUND_HALF_EVEN
print(round(payment, 2))