Limitation on loan calculator from a tutorial

This loan calculator doesn’t work if the principal number is like above 1 million. the result becomes NaN.
How do I fix it?

There are several issues with that code as it stands.

Can you please direct us to the code that you are using instead?

1 Like

The issues are in Mathematical logic or in the JS code?

In the JS code from my brief exploration. That’s why I’m attempting to start from the same point that @ash-f currently has, because I fail to understand how he is actually using the exact code from that article as it currently stands.

Let us get to the same set of code that he is using, and further beneficial progress can then be made from there.

2 Likes

True, I will be following this post.

Hi,

This is the function I used.

function calculateLoan(formname,resultelm){ 
    //get data
    var calcForm = document.getElementById(formname);

    var principal = parseInt(calcForm.elements['principal'].value);
    var payment = (calcForm.elements['payment'].value=='')?0:parseInt(calcForm.elements['payment'].value);
    var interest = (calcForm.elements['interest']=='')?0:parseInt(calcForm.elements['interest'].value);

    var rate = interest/100, noofpay = 12;

    var nper1 = Math.log((1-((principal/payment) * (rate/noofpay))));
    var nper2 = Math.log((1+(rate/noofpay)));
    nper = -(nper1/nper2);
    interestpaid=payment*nper-principal;
    nper = -Math.round((nper1/nper2));
    nyear=Math.floor(nper/12);
    nmonth=nper%12;
    if (nper>0)
    {
        if (nmonth==0)
        {
            period=nyear+" Year(s)";
        }
        else
        {
            period=nyear+" Year(s) and "+nmonth+" Month(s)";
        }
    }
    else
    {
        period="Invalid Values";
        interestpaid=0;
    }

    document.getElementById(resultelm).innerHTML = "Monthly: " + period + "<br />Total interest: " + interestpaid.toFixed(2)

}

Thank you. That code interacts quite a lot with HTML code.

Can you please supply the HTML code that you use, so that I can put together a test page of what you are experiencing?

Here is the html.

    <form name="loan-calc-form" id="loan-calc-form" onsubmit="calculateLoan('loan-calc-form','loan-calc-result');return false;">
    <div>
     Loan Amount<br /><input type=number name="principal"><br>
    </div>
     <div>
     Annual Percent Rate<br />
     <input type="number" name="interest"><br>
     </div>
      <div>
     Payment<br />
     <input type=number name="payment"><br>
      </div>
      <div id=buttonBlock>
    <button>Calculate</button>
      </div>
    </form>
    <div id="loan-calc-result"></div>

If the principal number is small like 100,000, it works.

In the meantime, I am attempting to put together a rough simulation of the form that you are using.

The function takes an argument with the id of the form being used, which I’ll call calculateForm.

It seems that you also haven’t supplied the code that runs the function. Sometimes people inappropriately use inline event handlers to do that. I will use a more appropriate addEventHandler instead to do that.

I don’t want to use a submit event, for the code doesn’t seem to be setup to manage that. Instead I will use a Calculate button.

  <p><button id="calculate">Calculate</button></p>
const calculateButton = document.querySelector("calculate");
calculateButton.addEventListener("click", function (evt) {
  calculateLoan("calculteForm", "result");
});

And we will need that result element too, which I’ll make as an output element.

<output id="result"></output>

Ahh, I see that a response has occurred, with the actual form that’s being used. Excellent.

I will cancel my efforts to simulate things, and use the supplied HTML form instead.

Here is the code that has been supplied, both the HTML and the JS code.

There seem to be problems before we get started. Clicking the calculate button takes you to a whole new page, which seems to be a problem.

When you were saying “This loan calculator doesn’t work if the principal number is like above 1 million.” does that mean that you have it working on values below 1 million?

Because if so, we haven’t been able to achieve that situation yet.

1 Like

it may not be 1 million, I didn’t check exact number. but 300000 was worked for sure.

As far as I researched, this line is the problem. may be the next line too.
This line returns NaN if the principal number is large.

var nperx = Math.log((1 - ((principal/payment)*(rate/noofpay)))); alert('nperx '+nperx);

Please see this

First I will attempt to fix the form submit problem, for the calculate button doesn’t seem to do anything, sending us to a new page instead. Pressing Enter on a form field doesn’t seem to do anything different either, sending us to a new page too.

To fix that I will replace the inline event handler. Inline events are the cause of many problems.

I will replacing it with JS addEventListener code, that uses evt.preventDefault() to prevent the default form behaviour of submitting to a new page.

 const calculateForm = document.querySelector("#loan-calc-form");
 calculateForm.addEventListener("submit", function (evt) {
   evt.preventDefault();
 });

Now the form behaves more appropriately, by not submitting to a new page

We can now add the calculateLoan code:

 const calculateForm = document.querySelector("#loan-calc-form");
 calculateForm.addEventListener("submit", function (evt) {
   evt.preventDefault();
   calculateLoan('loan-calc-form','loan-calc-result');
 });

The form now runs the calculate loan code, but I am informed in the browser console that an error occurs, because a property value cannot be read.

Okay, I will stop trying to get that earlier code working, and take a diversion to the more recent set of code that you have just posted at https://jsfiddle.net/18xepnga/

I have the code already working on my actual site and it’s implemented in Wordpress.
So the code I pasted went something wrong when I was fiddling around.
But I think I can fix it later.
Main problem is that the original tutorial doesn’t work properly.

Yes, we are in full agreement about that.

There are several different things that I could do now, such as working at getting the original tutorial to work, or helping you to get something else working.

What do you think that I should do?

Yes any way is appreciated.
But first I want to know why this line returns NaN when the principal number is large.
Could it be the limitation of JS itself?

var nper1 = Math.log((1-((principal/payment) * (rate/noofpay))));

16 posts were split to a new topic: Using the compound interest formula

Hmm, this calculator shows different result.
Is your logic something different?

www.watrust. com/calculators/personal-loans/length-to-pay-off-loan/
(Please remove the space, I can not post this url somehow)