Skip to content
This repository was archived by the owner on Jan 15, 2025. It is now read-only.

Commit b15de7d

Browse files
committed
improve example
1 parent 27cea5c commit b15de7d

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

examples/mortgage.ts

+20-10
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,28 @@ import { pow } from "./pow.mjs";
44
const one = new Decimal128("1");
55
const paymentsPerYear = new Decimal128("12");
66

7-
function calculateMonthlyPayment(p: string, r: string, y: string): Decimal128 {
8-
const principal = new Decimal128(p);
9-
const annualInterestRate = new Decimal128(r);
10-
const years = new Decimal128(y);
7+
function calculateMonthlyPayment(
8+
principal: Decimal128,
9+
annualInterestRate: Decimal128,
10+
years: Decimal128
11+
): Decimal128 {
1112
const monthlyInterestRate = annualInterestRate.divide(paymentsPerYear);
1213
const paymentCount = paymentsPerYear.multiply(years);
1314
const onePlusInterestRate = monthlyInterestRate.add(one);
14-
const ratePower = pow(onePlusInterestRate, Number(paymentCount));
15-
16-
const x = principal.multiply(monthlyInterestRate);
17-
18-
return x.multiply(ratePower).divide(ratePower.subtract(one));
15+
const ratePower = pow(
16+
onePlusInterestRate,
17+
Number(paymentCount.toString({ numDecimalDigits: 0 }))
18+
);
19+
return principal
20+
.multiply(monthlyInterestRate)
21+
.multiply(ratePower)
22+
.divide(ratePower.subtract(one));
1923
}
2024

21-
console.log(calculateMonthlyPayment("5000000", "0.05", "30").toString());
25+
console.log(
26+
calculateMonthlyPayment(
27+
new Decimal128("5000000"),
28+
new Decimal128("0.05"),
29+
new Decimal128("30")
30+
).toString({ numDecimalDigits: 2 })
31+
);

0 commit comments

Comments
 (0)