Skip to content

Mortgage Calculator — Rust 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 Rust 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.

pub fn monthly_payment(principal: f64, rate_pct: f64, years: i64) -> Option<f64> {
    if !(principal.is_finite() && rate_pct.is_finite()) || principal <= 0.0 || years <= 0 {
        return None;
    }

    let r = rate_pct / 100.0 / 12.0;
    let n = (years * 12) as f64;
    let payment = if r == 0.0 {
        principal / n
    } else {
        let growth = (1.0 + r).powf(n);
        principal * r * growth / (growth - 1.0)
    };
    Some((payment * 100.0 + 0.5).floor() / 100.0)
}

// Example:
//   monthly_payment(300000.0, 6.0, 30) -> Some(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 →