Compound Interest Calculator — JavaScript source
Project investment growth with any compounding frequency, scheduled contributions and inflation adjustment. Yearly breakdown, growth curve and CSV export — runs entirely in your browser.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* compound-interest-calculator - compound growth projection.
*
* Display snippet: ports the core project() math from the TypeScript lib
* (src/lib/interest.ts). The full projection (contributions, inflation,
* per-year rows) lives in the TypeScript/Go sources.
*
* Semantics: monthly simulation with the monthly rate set to the exact
* equivalent of the stated compounding frequency — (1 + r/n)^(n/12) - 1 —
* so the effective annual rate is preserved for every supported
* frequency. Returns the final balance rounded to 2 decimals, or null on
* invalid input (negative principal, non-integer years, unsupported
* frequency, non-finite values).
*/
const VALID_COMPOUNDS = new Set([1, 2, 4, 12, 365]);
/** Round to 2 decimals, absorbing binary float noise. */
function round2(n) {
return Math.round((n + Number.EPSILON) * 100) / 100;
}
function project(principal, ratePct, years, compoundsPerYear) {
if (![principal, ratePct, years, compoundsPerYear].every(Number.isFinite)) return null;
if (principal < 0 || years < 0 || !Number.isInteger(years)) return null;
if (!VALID_COMPOUNDS.has(compoundsPerYear)) return null;
const monthlyRate = Math.pow(1 + ratePct / 100 / compoundsPerYear, compoundsPerYear / 12) - 1;
let balance = principal;
for (let month = 0; month < years * 12; month++) {
balance = balance * (1 + monthlyRate);
}
return round2(balance);
}
// Example:
// project(10000, 5, 10, 12) -> 16470.09
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 →