The formula here would be:
P*(1+r)^y + sum_{n=0}^{y*12-1} M*(1+r)^(y-n/12)
where P is the original amount, r is the rate, y is the number of years and M is the monthly contribution.
<html>
<head>
<script type="text/javascript">
function calculate(original, monthly, rate, years) {
var multiplier1 = Math.pow((1+rate),years);
var value1 = original*multiplier1;
var multiplier2 = 0;
for(var i=0; i<(years*12); i++) {
multiplier2 = multiplier2 + Math.pow((1+rate), years-i/12);
}
var value2 = monthly*multiplier2;
var total = value1 + value2;
var o = '<b>Total:</b> '+total;
o = o + '<br>';
o = o + '<br><b>Original:</b> '+original;
o = o + '<br><b>Multiplier1:</b> '+multiplier1;
o = o + '<br><b>Value1:</b> '+value1;
o = o + '<br>';
o = o + '<br><b>Monthly:</b> '+monthly;
o = o + '<br><b>Multiplier2:</b> '+multiplier2;
o = o + '<br><b>Value2:</b> '+value2;
output(o);
return total;
}
function output(outputVal) { // Output Function
document.getElementById('myoutput').innerHTML = outputVal;
}
function documentReady() { // Document Ready Function
calculate(100000, 120, .05, 5);
}
</script>
</head>
<body onload="documentReady();">
<div id="myoutput"></div>
</body>
</html>
<head>
<script type="text/javascript">
function calculate(original, monthly, rate, years) {
var multiplier1 = Math.pow((1+rate),years);
var value1 = original*multiplier1;
var multiplier2 = 0;
for(var i=0; i<(years*12); i++) {
multiplier2 = multiplier2 + Math.pow((1+rate), years-i/12);
}
var value2 = monthly*multiplier2;
var total = value1 + value2;
var o = '<b>Total:</b> '+total;
o = o + '<br>';
o = o + '<br><b>Original:</b> '+original;
o = o + '<br><b>Multiplier1:</b> '+multiplier1;
o = o + '<br><b>Value1:</b> '+value1;
o = o + '<br>';
o = o + '<br><b>Monthly:</b> '+monthly;
o = o + '<br><b>Multiplier2:</b> '+multiplier2;
o = o + '<br><b>Value2:</b> '+value2;
output(o);
return total;
}
function output(outputVal) { // Output Function
document.getElementById('myoutput').innerHTML = outputVal;
}
function documentReady() { // Document Ready Function
calculate(100000, 120, .05, 5);
}
</script>
</head>
<body onload="documentReady();">
<div id="myoutput"></div>
</body>
</html>
Output:
Total: 135798.95858737087
Original: 100000
Multiplier1: 1.2762815625000001
Value1: 127628.15625000001
Monthly: 120
Multiplier2: 68.09001947809055
Value2: 8170.802337370867
This post was reposted from http://scottizu.wordpress.com/2014/07/30/a-javascript-example-to-calculate-net-worth-based-on-monthly-contributions/, originally written on July 30th, 2014.
No comments:
Post a Comment