Mortgage Calculator — Python source
Compute monthly payments, the full amortization schedule and total interest, with extra-payment what-if analysis showing months and interest saved — runs entirely in your browser.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""
mortgage-calculator - amortized monthly payment.
Display snippet: ports the core monthly_payment() formula from the
TypeScript lib (src/lib/mortgage.ts). The full amortization schedule
(integer-cent tracking, extra payments, payoff dates) lives in the
TypeScript/Go sources.
Standard amortization formula: P*r*(1+r)**n / ((1+r)**n - 1) with
r = rate_pct/100/12 and n = years*12. A zero rate divides the principal
evenly. Returns the payment rounded to cents, or None on invalid input.
Standard library only.
"""
import math
def monthly_payment(principal, rate_pct, years):
if not all(math.isfinite(v) for v in (principal, rate_pct)):
return None
if principal <= 0 or years <= 0 or not isinstance(years, int):
return None
r = rate_pct / 100 / 12
n = years * 12
if r == 0:
payment = principal / n
else:
growth = (1 + r) ** n
payment = principal * r * growth / (growth - 1)
return math.floor(payment * 100 + 0.5) / 100
# Example:
# monthly_payment(300000, 6, 30) -> 1798.65
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →