Skip to content

Instantly share code, notes, and snippets.

@littledian
Created February 10, 2023 01:24
Show Gist options
  • Save littledian/b4242200e8a67b8d346d293f75a5d293 to your computer and use it in GitHub Desktop.
Save littledian/b4242200e8a67b8d346d293f75a5d293 to your computer and use it in GitHub Desktop.
贷款计算器
const yearRate = 0.043; // 年利率
const monthRate = yearRate / 12; // 月利率
const totalMonth = 360; // 总共还款月数
// 等额本息,计算每月还款比例
let array = [];
for (let i = 0; i < totalMonth; i++) {
const total = array.reduce((prev, cur) => prev + cur, 0);
array.push(1 - total * monthRate);
}
array = array.reverse().map((v) => v / 360);
const total = array.reduce((prev, cur) => prev + cur);
const rate = 1 / total;
array = array.map((v) => v * rate); // 每个月还款的本金占比
const perMonthTotal = array.at(-1); // 每个月还款的总额
const targetYear = 10; // 假设十年还清贷款
// 前面十年总的还款额
const prevTotal = perMonthTotal * targetYear * 12;
// 前面十年总的还款本金
const prevPure = array.slice(0, targetYear * 12).reduce((prev, cur) => prev + cur);
// 剩下需要还的本金
const restPure = 1 - prevPure;
// 总的花费
const totalA = prevTotal + restPure;
console.log(`------------在第${targetYear}年还清贷款,需要一次性付清的本金`, restPure);
console.log(`------------在第${targetYear}年还清贷款总的花费`, totalA);
// 在还款的第一期选择提前还款,每月还款额不变,缩短贷款年限,使得十年还清贷款
// 重新计算本金和利息
let newArray = [];
for (let i = 0; i < targetYear * 12; i++) {
const total = newArray.reduce((prev, cur) => prev + cur, 0);
newArray.push(1 - total * monthRate);
}
newArray = newArray.reverse().map((v) => v / (targetYear * 12));
const newRate = newArray.reduce((prev, cur) => prev + cur); // 还款的本金比例
const newPure = newRate * targetYear * 12 * perMonthTotal; // 按照等额本息十年总共还款的本金
const newRestPure = 1 - newPure; // 第一个月提前还贷需要还款的本金
console.log(`------------在第${targetYear}还清贷款,第一个月需要提前还掉的贷款`, newRestPure);
// 第十年一次性还清和第一个月还款的比例
let revenueRate = restPure / newRestPure;
// 计算年化收益
revenueRate = Math.pow(Math.E, Math.log(revenueRate) / 10) - 1;
console.log(`------------提前还清和十年后一次付清成本相当的时候,需要达到的收益`, revenueRate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment