Creating a JavaScript tool for calculating compound interest future values

I'm currently facing the challenge of translating an equation from Google Sheets into JavaScript, however, I'm getting divergent results.

I aim to reproduce the formula found here:

Original equation:

F = P*(1+rate)^nper + A*( ((1+rate)^nper - 1)/rate )

This is my current attempt: (Note that variable names in my code snippet differ)

v = ((p*(Math.pow((1+rate),nper))) + (A*(Math.pow((1+rate),nper - 1))/rate));


Additional Details from the original source:
r = nominal annual interest rate (decimal)
n = number of compounding periods per year
p = number of payment periods per year
rate = rate per payment period
nper = total number of payment periods
A = an amount added to the principal at the end of each payment period

rate = ((1+r/n)^(n/p))-1
nper = p * t
Total Payments = A*nper
Total Interest = F - P - Total Payments


Full context (My Vue Code):


        var app = new Vue({
          el: '#app',
          data: {
            principal: 0,
            interest_rate: 0,
            time_invested: 0,
            additional_investment: 0,
            additional_investment_frequency : 1,
            options: {
                additional_investment_frequency: {
                "1": "Yearly",
                "12": "Monthly",
                "26": "Fortnightly",
                "52": "Weekly",
                "365": "Daily"
                }
            },
            compound_frequency : 1,
            options: {
                compound_frequency: {
                "1": "Yearly",
                "12": "Monthly"
                }
            }
          },
          methods:{
        },
          computed: {
            total_pay_periods: function () {
                // calculate total number of pay periods
                total_pay_periods = parseFloat(this.additional_investment_frequency) * parseFloat(this.time_invested);
                return parseFloat(this.additional_investment_frequency) * parseFloat(this.time_invested);
            },
            total_additional_investment: function () {
                // calculate total number of pay periods
                total_pay_periods = parseFloat(this.additional_investment_frequency) * parseFloat(this.time_invested);
                // times total pay periods by additional investment installment amount to get overall total additional investment
                return parseFloat(this.additional_investment) *  total_pay_periods;
            },
            rate: function () {
                ir = parseFloat(this.interest_rate) / 100;
                cf = parseFloat(this.compound_frequency);
                aif = parseFloat(this.additional_investment_frequency);
                return (Math.pow((1+ir/cf),(cf/aif))-1);
                // return (((1+ir/cf)^(cf/aif))-1);
            },
            future_value: function () {
                p = parseFloat(this.principal);
                r = parseFloat(this.rate);
                tpp = parseFloat(this.total_pay_periods);
                ai = parseFloat(this.additional_investment);

                // F = P*(1+rate)^nper + A*( ((1+rate)^nper - 1)/rate )
                // https://www.vertex42.com/Calculators/compound-interest-calculator.html#rate-per-period

                // calculate final future value
                v = ((p*(Math.pow((1+r),tpp))) + (ai*(Math.pow((1+r),tpp - 1))/r));
                // convert to 2 decimal places
                return  v.toFixed(2);
            }
          }
        })

Answer №1

Your second term contains a mistake:

(A*(Math.pow((1+rate),nper - 1))/rate));
The "-1" should not be inside the power function. The correct form is
(A*(Math.pow((1+rate),nper) - 1)/rate));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to update object values only when changes occur, and leave the object unchanged if no changes

There is an object named ApiData1 containing key-value pairs, including color values within properties. The colors are updated based on the numberOfProjects value from ApiData2, with specific ranges dictating the color updates. This setup is functioning co ...

Dynamic backdrop featuring engaging content

I am currently working on a WordPress website that features a dynamic background. While I have successfully implemented movement to the background, the content on the site remains static and unaffected by scrolling. The background does not move alongside t ...

What is the best way to make my button activate as if it were being clicked for the very first time?

Currently, I am in the process of a project that involves generating a quote from an API. Below is the code snippet I am using: $("#btn").on("click",function(){ $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_ ...

Invoke a PHP function located in a separate file using a JavaScript function to fetch data from a database

How can I properly call a PHP function from a JavaScript function located in a different file? I am trying to pass a variable from an onClick function in JavaScript to a PHP function, which will then access a MySQL database to retrieve data. However, my c ...

jQuery must provide the complete object rather than just the data within it

What is the best way to retrieve the entire <div class="loan_officer_apply_now_link"><a href="">APPLY NOW!</a></div> At present, only the "a" element content is being returned <a href="">APPLY NOW!</a> Test Code $( ...

Angular : How can a single item be transferred from an array list to another service using Angular services?

How to Transfer a Single List Item to the Cart? I'm working on an Angular web application and I need help with transferring a single item from one service to another service and also displaying it in a different component. While I have successfully i ...

HTML5 enables the creation of an imperceptible scrollbar

I am looking to make my scrollbar invisible without it being visible however, I still want it to function when hovering over the box Also, I need it to work smoothly on both tablets and computers, which is why I have opted for using html5 I would great ...

When no files are uploaded, req.files.upload.length will return zero; however, if more than one file is uploaded, it will return the total number of files. In the

When using this loop, the variable “req.files.upload.length” will return the file count if 0 or more than one files are uploaded. However, it returns the file size if only one file is uploaded. Why does this happen? This is the upload handler: app.po ...

Using Google Maps API v3 to Convert User-Input Coordinates into LatLng Points

I'm a beginner when it comes to using Google Maps and I'm having trouble with turning coordinates input by a user into moving a marker on my map. The goal is for the marker to pan to the specific coordinates entered by the user. Unfortunately, my ...

Tips for testing Vue.js metaInfo

While working on writing some unit tests, I have a component that utilizes Vue-meta to set meta information. Here is what my Component code looks like: export default { ... metaInfo () { const expertName = this.getBlogInfo.blog.author.trim() co ...

Performing simultaneous updates to multiple records using CAML/jQuery in Sharepoint (Batch updates)

I am working on updating multiple records in Share Point using jQuery and CAML queries. While it's easy to update a single record with the current code, I need to handle 20 Products simultaneously for this particular project. Instead of looping throug ...

Having trouble getting the .replace() Javascript function to work on mobile devices?

I have a code snippet for implementing Google Analytics. Here it is: $(function () { $('.plan-choose-btn a').bind('click', function(e) { //ga load image <% String myaccGAEventUrl = trackGoogleAnalyticsEvent(requ ...

Where can I find the code for printing a diamond shape using JavaScript?

I'm looking to design a tool where users can input odd numbers and generate diamond-shaped patterns using asterisks. For example: Enter an odd number: 5 * *** ***** *** * ...

Angular2 drag and drop feature becomes functional only after eliminating an irrelevant section from the template

Currently, I am harnessing the power of Angular2 to incorporate drag and drop functionalities. Specifically, my goal is to enable the movement of "windows" within different "sessions", with each window containing a set of bookmarks. Upon testing, I have o ...

Assigning HTML code to a variable in Vue.js: A Step-by-Step Guide

I am looking to store HTML in a variable within my Vue.js 3 setup() function so that I can use it later in the template. However, when I attempt to do so, I encounter an error message stating "VueCompilerError: Invalid end tag.". It appears that ...

swapping the final word in a string with Node.js or JavaScript

var str = "Demo Docs Version 1.0.1"; var gotWord = str.split(" ").splice(-1)[0] str = str.replace(gotWord, "testing"); console.log(str); If there is a space between words, I can replace the last word. But how do I replace the last word when ...

Importing multiple exports dynamically in Next.js

My current setup involves using a third-party package that I load dynamically in Next.js: const am5 = dynamic(() => import("@amcharts/amcharts5"), {ssr: false}) The imported amcharts5 consists of various exports and imports, such as: export { ...

What is the method to have VIM recognize backticks as quotes?

Currently working in TypeScript, I am hoping to utilize commands such as ciq for modifying the inner content of a template literal. However, it appears that the q component of the command only recognizes single and double quotation marks as acceptable ch ...

Guide on how to selectively expand a particular node within multiple jstree instances on a single webpage

i'm having difficulty with opening a specific jstree node. i have several jstree instances on a single page and would like to programmatically control the opening and closing of nodes. Query: how can I open the banana node programmatically? below i ...

What steps are involved in creating a completely self-contained application that can be deployed without relying on Azure services?

During a meeting with management today, it was mentioned that the goal is to develop a self-contained application that could operate without relying on Azure. Can someone provide more information about how this can be achieved? Our current tech stack incl ...