Skip to content

@stdlib · money · loans

loan.monthly-payment

What does this loan cost per month?

v1.0.05 cases pass5 refusals holdmoneyloans

POST the call — JSON in, JSON out, pinned to this versionPAGE the same formula as one screen, for somebody who wants the answer

What it does

The annuity formula: a constant monthly payment that clears the principal over n months at a monthly rate r.

payment = principal * r / (1 - (1 + r) ^ -n)

A zero-interest loan is the case that formula cannot take — it divides by zero — so it is answered directly.

Call it

One request, JSON in, JSON out. Each example is filled in with the formula's own first case, so it answers as it stands.

curl

curl -X POST 'https://ofi.dev/@stdlib/loan.monthly-payment@1.0.0/call' \
  -H 'Content-Type: application/json' \
  -d '{"principal":200000,"annualRatePercent":6,"years":30}'

# the same call as a URL, which is linkable and cacheable
curl 'https://ofi.dev/@stdlib/loan.monthly-payment@1.0.0/call?principal=200000&annualRatePercent=6&years=30'

JavaScript

const response = await fetch('https://ofi.dev/@stdlib/loan.monthly-payment@1.0.0/call', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    "principal": 200000,
    "annualRatePercent": 6,
    "years": 30
  })
});
const answer = await response.json();
if (!response.ok) throw new Error(answer.message);  // 422 carries kind, path, field, label
console.log(answer);

Python

import json, urllib.error, urllib.request

request = urllib.request.Request(
    'https://ofi.dev/@stdlib/loan.monthly-payment@1.0.0/call',
    data=json.dumps({'principal': 200000, 'annualRatePercent': 6, 'years': 30}).encode(),
    headers={'Content-Type': 'application/json'},
)
try:
    with urllib.request.urlopen(request) as response:
        print(json.load(response))
except urllib.error.HTTPError as refusal:
    print(refusal.code, json.load(refusal))

Ruby

require 'json'
require 'net/http'

response = Net::HTTP.post(
  URI('https://ofi.dev/@stdlib/loan.monthly-payment@1.0.0/call'),
  JSON.generate({ 'principal' => 200000, 'annualRatePercent' => 6, 'years' => 30 }),
  'Content-Type' => 'application/json'
)
answer = JSON.parse(response.body)
raise answer['message'] unless response.code == '200'
pp answer

A refusal comes back as 422, naming the field that caused it.

It proves itself5 / 5

5 cases, named in business language. The build does not produce this page unless every one of them passes, and the answers below are the compiled formula's rather than a transcription.

  • textbook 30-year mortgage

    Try it
    principal 200000annualRatePercent 6years 30→monthlyPayment 1199.1totalPaid 431676totalInterest 231676payments 360
  • same loan, 15 years

    Try it
    principal 200000annualRatePercent 6years 15→monthlyPayment 1687.71totalPaid 303787.8totalInterest 103787.8payments 180
  • car loan

    Try it
    principal 25000annualRatePercent 3.9years 5→monthlyPayment 459.29totalPaid 27557.4totalInterest 2557.4payments 60
  • interest free

    Try it
    principal 12000annualRatePercent 0years 2→monthlyPayment 500totalPaid 12000totalInterest 0payments 24
  • one year, small

    Try it
    principal 1000annualRatePercent 12years 1→monthlyPayment 88.85totalPaid 1066.2totalInterest 66.2payments 12

What it refuses5 / 5

A refusal is correct behaviour, so it is specified too. Each of these raises the failure the bundle wrote down — try one and watch the message land on the field that caused it.

  • nothing borrowed

    Try it
    principal 0annualRatePercent 3.5years 20→.principal: constraint 'positive' failed
  • a rate of more than a hundred percent

    Try it
    principal 250000annualRatePercent 120years 20→.annualRatePercent: constraint 'notNegative' failed
  • a loan over no years

    Try it
    principal 250000annualRatePercent 3.5years 0→.years: constraint 'atLeastOne' failed
  • a term in half years, where the term is whole months of payments

    Try it
    principal 250000annualRatePercent 3.5years 20.5→.years: expected Int, got number
  • no term at all

    Try it
    principal 250000annualRatePercent 3.5years missing→.years: expected Int, got undefined

The function

This is the whole of it. There is no other copy: the endpoint above runs this program, and the cases were run against its compilation during the build.

formula.elo

# What does this loan cost per month?## The annuity formula: a constant monthly payment that clears the principal# over n months at a monthly rate r.##     payment = principal * r / (1 - (1 + r) ^ -n)## A zero-interest loan is the case that formula cannot take — it divides by# zero — so it is answered directly. let  loanPayment = fn( input ~>    let      months = input.years * 12,      rate = input.annualRatePercent / 100 / 12,      payment = if rate == 0                then input.principal / months                else input.principal * rate / (1 - (1 + rate) ^ -months),      monthly = round(payment, 2),      total = round(monthly * months, 2)    in      {        monthlyPayment: monthly,        totalPaid: total,        totalInterest: round(total - input.principal, 2),        payments: months      }  )in  { formula: loanPayment } 

types.elo

Input = {  principal: Float(p | positive: p > 0),  annualRatePercent: Float(r | notNegative: r >= 0 && r < 100),  years: Int(y | atLeastOne: y >= 1 && y <= 50)} Output = {  monthlyPayment: Float,  totalPaid: Float,  totalInterest: Float,  payments: Int} 

Compiled · JavaScript

(function(_) { function kAdd(l, r) { if (DateTime.isDateTime(l) && Duration.isDuration(r)) return l.plus(r); if (Duration.isDuration(l) && DateTime.isDateTime(r)) return r.plus(l); if (Duration.isDuration(l) && Duration.isDuration(r)) return l.plus(r); return l + r; } function kDiv(l, r) { if (Duration.isDuration(l) && typeof r === 'number') return Duration.fromMillis(l.toMillis() / r); return l / r; } function kEq(l, r) { if (Duration.isDuration(l) && Duration.isDuration(r)) return l.toMillis() === r.toMillis(); if (DateTime.isDateTime(l) && DateTime.isDateTime(r)) return l.toMillis() === r.toMillis(); if (Array.isArray(l) && Array.isArray(r)) { if (l.length !== r.length) return false; for (let i = 0; i < l.length; i++) if (!kEq(l[i], r[i])) return false; return true; } if (typeof l === 'object' && typeof r === 'object' && l !== null && r !== null && !Array.isArray(l) && !Array.isArray(r)) { const keysL = Object.keys(l); const keysR = Object.keys(r); if (keysL.length !== keysR.length) return false; for (const key of keysL) if (!(key in r) || !kEq(l[key], r[key])) return false; return true; } return l == r; } function kMember(o, k) { if (o === null || typeof o !== 'object') return null; return Object.prototype.hasOwnProperty.call(o, k) ? o[k] : null; } function kMul(l, r) { if (Array.isArray(l) || Array.isArray(r)) throw new Error("Array multiplication is not supported"); if (Duration.isDuration(l)) return Number.isInteger(r) ? l.mapUnits(u => u * r) : Duration.fromMillis(l.toMillis() * r); if (Duration.isDuration(r)) return Number.isInteger(l) ? r.mapUnits(u => u * l) : Duration.fromMillis(r.toMillis() * l); return l * r; } function kNeg(v) { if (Duration.isDuration(v)) return Duration.fromMillis(-v.toMillis()); return -v; } function kPow(l, r) { return Math.pow(l, r); } function kRound(x) { return x < 0 ? -Math.round(-x) : Math.round(x); } function kRoundTo(x, n) { const f = Math.pow(10, n); return kRound(x * f) / f; } function kSub(l, r) { if (DateTime.isDateTime(l) && Duration.isDuration(r)) return l.minus(r); if (DateTime.isDateTime(l) && DateTime.isDateTime(r)) return Duration.fromMillis(l.toMillis() - r.toMillis()); if (Duration.isDuration(l) && Duration.isDuration(r)) return l.minus(r); return l - r; } function pFail(p, m, c, k, l) { return { success: false, path: p, message: m || '', value: null, cause: c || [], kind: k || 'schema', label: l }; } function pFloat(v, p) { if (typeof v === 'number') return pOk(v, p); if (typeof v === 'string' && /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(v.trim())) return pOk(parseFloat(v.trim()), p); return pFail(p, 'expected Float, got ' + (v === null ? 'Null' : typeof v === 'string' ? JSON.stringify(v) : typeof v)); } function pInt(v, p) { if (typeof v === 'number' && Number.isInteger(v)) return pOk(v, p); if (typeof v === 'string' && /^[+-]?\d+$/.test(v.trim())) return pOk(parseInt(v.trim(), 10), p); return pFail(p, 'expected Int, got ' + (v === null ? 'Null' : typeof v === 'string' ? JSON.stringify(v) : typeof v)); } function pOk(v, p) { return { success: true, path: p, message: '', value: v, cause: [] }; } function pSchema(props, extrasMode, extrasParser) { const known = props.map(pr => pr[0]); return (v, p) => { if (typeof v !== 'object' || v === null || Array.isArray(v)) return pFail(p, 'expected object, got ' + (v === null ? 'Null' : typeof v)); const o = {}; for (const [key, parser, optional] of props) { if (optional && v[key] == null) continue; const r = parser(v[key], p + '.' + key); if (!r.success) return pFail(p, null, [Object.prototype.hasOwnProperty.call(v, key) ? r : { ...r, kind: 'missing' }]); o[key] = r.value; } if (extrasMode === 'closed') { for (const k in v) if (!known.includes(k)) return pFail(p + '.' + k, 'unexpected attribute'); } else if (extrasMode === 'typed' && extrasParser) { for (const k in v) { if (known.includes(k)) continue; const re = extrasParser(v[k], p + '.' + k); if (!re.success) return pFail(p, null, [re]); o[k] = re.value; } } return pOk(o, p); }; } function pSubtype(baseParser, checks) { return (v, p) => { const r = baseParser(v, p); if (!r.success) return r; for (const [message, label, fn] of checks) { if (!fn(r.value)) return pFail(p, message, [], 'constraint', label); } return r; }; } function pUnwrap(r) { if (r.success) return r.value; function findError(e) { if (e.message) return e; if (e.cause && e.cause[0]) return findError(e.cause[0]); return e; } const err = findError(r); const e = new Error((err.path || '.') + ': ' + (err.message || 'type error')); e.kind = err.kind || 'schema'; e.path = err.path || '.'; if (err.label) e.label = err.label; throw e; } return (() => { const _module_0 = (() => { const loanPayment = (input) => (() => { const months = kMul(kMember(input, "years"), 12); const rate = kDiv(kDiv(kMember(input, "annualRatePercent"), 100), 12); const payment = ((kEq(rate, 0)) ? (kDiv(kMember(input, "principal"), months)) : (kDiv(kMul(kMember(input, "principal"), rate), kSub(1, kPow(kAdd(1, rate), kNeg(months)))))); const monthly = kRoundTo(payment, 2); const total = kRoundTo(kMul(monthly, months), 2); return ({monthlyPayment: monthly, totalPaid: total, totalInterest: kRoundTo(kSub(total, kMember(input, "principal")), 2), payments: months}); })(); return ({formula: loanPayment}); })(); const formula = kMember(_module_0, "formula"); return (() => { const _p_Input = pSchema([["principal", pSubtype(pFloat, [["constraint 'positive' failed", "positive", (p) => p > 0]]), false], ["annualRatePercent", pSubtype(pFloat, [["constraint 'notNegative' failed", "notNegative", (r) => r >= 0 && r < 100]]), false], ["years", pSubtype(pInt, [["constraint 'atLeastOne' failed", "atLeastOne", (y) => y >= 1 && y <= 50]]), false]], 'closed', null); const Input = (v) => pUnwrap(_p_Input(v, '')); const _p_Output = pSchema([["monthlyPayment", pFloat, false], ["totalPaid", pFloat, false], ["totalInterest", pFloat, false], ["payments", pInt, false]], 'closed', null); const Output = (v) => pUnwrap(_p_Output(v, '')); return Output(formula(Input(_))); })(); })(); })
Join the waiting listto publish your own functions.

Other examples