Skip to content

Commit bc3f3b7

Browse files
fix: prevent Infinity in effectiveAnnualReturn when initialBalance is 0
When initialBalance is 0, the effectiveAnnualReturn calculation was dividing by zero, resulting in Infinity. Now handles this edge case by: - Using totalContributions as the base when initialBalance is 0 - Returning 0 when both initialBalance and totalContributions are 0 - Maintaining original calculation for non-zero initial balances This ensures accurate return metrics for accounts starting from zero.
1 parent 488e314 commit bc3f3b7

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "retirement-calculator",
3-
"version": "1.1.0",
3+
"version": "1.1.1",
44
"description": "A versatile retirement financial planning tool for calculating savings, inflation impact, and withdrawal strategies.",
55
"main": "dist/index.js",
66
"types": "dist/index.d.ts",

src/RetirementCalculator.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -545,8 +545,16 @@ export default class RetirementCalculator {
545545
}
546546

547547
// Calculate summary statistics
548-
const effectiveAnnualReturn =
549-
Math.pow(balance / initialBalance, 1 / totalYears) - 1;
548+
let effectiveAnnualReturn: number;
549+
if (initialBalance === 0) {
550+
// When starting from 0, calculate return based on contributions instead
551+
effectiveAnnualReturn =
552+
totalContributions > 0
553+
? Math.pow(balance / totalContributions, 1 / totalYears) - 1
554+
: 0;
555+
} else {
556+
effectiveAnnualReturn = Math.pow(balance / initialBalance, 1 / totalYears) - 1;
557+
}
550558
const averageMonthlyReturn =
551559
monthlyTimeline.reduce(
552560
(sum, entry) => sum + entry.currentMonthlyReturn,

0 commit comments

Comments
 (0)