Mortgage Calculator — Kotlin 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 Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.
// mortgage-calculator — amortized monthly payment.
//
// Language: Kotlin (1.9, standard library only)
// Source: CosmoDev polyglot showcase port of the Mortgage Calculator
// tool, ported from src/lib/mortgage.ts (the canonical
// TypeScript implementation).
// Tool: https://dev.cosmolabs.org/tools/mortgage-calculator
// License: display source — part of CosmoDev's polyglot tool pages.
//
// Display snippet: ports the core monthlyPayment() formula from the
// TypeScript lib. The full amortization schedule (integer-cent tracking,
// extra payments, payoff dates) lives in the TypeScript/Go sources.
//
// Semantics: standard amortization formula P*r*(1+r)^n / ((1+r)^n - 1)
// with r = ratePct/100/12 and n = years*12. A zero rate divides the
// principal evenly across n months. Returns the payment rounded to
// cents, or null on invalid input (non-positive principal, non-positive
// years, non-finite values).
import kotlin.math.floor
import kotlin.math.pow
/** Round to 2 decimals, half-up (mirrors the TS Math.round). */
fun round2(n: Double): Double = floor(n * 100.0 + 0.5) / 100.0
fun monthlyPayment(principal: Double, ratePct: Double, years: Int): Double? {
if (!principal.isFinite() || !ratePct.isFinite()) return null
if (principal <= 0.0 || years <= 0) return null
val r = ratePct / 100.0 / 12.0
val n = years * 12.0
val payment = if (r == 0.0) {
principal / n
} else {
val growth = (1.0 + r).pow(n)
principal * r * growth / (growth - 1.0)
}
return round2(payment)
}
fun main() {
// Example:
// monthlyPayment(300000.0, 6.0, 30) -> 1798.65
val result = monthlyPayment(300000.0, 6.0, 30)
check(result == 1798.65) { "expected 1798.65, got $result" }
// A zero rate divides the principal evenly.
check(monthlyPayment(300000.0, 0.0, 30) == 833.33) { "expected 833.33 at a zero rate" }
// Invalid inputs are rejected, never clamped.
check(monthlyPayment(-1.0, 6.0, 30) == null) { "non-positive principal" }
check(monthlyPayment(300000.0, 6.0, 0) == null) { "non-positive years" }
check(monthlyPayment(Double.POSITIVE_INFINITY, 6.0, 30) == null) { "non-finite value" }
println("ok")
}
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 →