python - 用 Python 比较贷款

标签 python rounding

我正在为我的 Python 类(class)做作业。我几乎弄明白了,但我的输出与原始问题中显示的略有不同。当利率为 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

最佳答案

当您处理金钱时,请使用 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

Bankers' rounding会是:

decimal.ROUND_HALF_EVEN

Round to nearest with ties going to nearest even integer.

with decimal.localcontext() as ctx:
    ctx.rounding = decimal.ROUND_HALF_EVEN
    print(round(payment, 2))

关于python - 用 Python 比较贷款,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35079545/

相关文章:

python - 将字典中的下一项与上一项进行比较

python - Pycharm (@property) 和 (@x.setter) 自动生成

perl - Perl 中的四舍五入 float ..大效率低但有效的解决方案

python - 如何舍入一个numpy数组?

delphi - 从 EndOfTheMonth(date) 到 Variant 值的错误转换

html - 百分比舍入区域的 CSS 修复

Python 3.5 CentOS 7

python - 使用 NumPy 快速求出所有行对的差异

python - 在自定义层中禁用了 Tensorflow 2 急切执行

c 浮点向下舍入