Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    New to the CF scene
    Join Date
    Mar 2009
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Need Help with JavaScript (Building a variety of calculators)

    Hey Everyone ^^

    Im working on my final project for DOM and I am having some issues with JavaScript. I have never been a huge fan of it (im much better with PHP) and I have to make a financial loan site. The site is required to have several calculators that calculate loans. I was given an example site with several formulas and working calculators on it, I have to take those formulas and make them my own, which I did with a couple of the easier ones, the ones im having trouble with are the ones that require the use of algebra, I know how to do them on paper i could do them all day on paper lol, but i dont know how to make JavaScript do them. The ones im having issues with are linked below, unfortunately I cant give you the actual link but thats because its on my schools server, but I took some screenshots and posted them.

    Here are links to the formulas Im using, the things I cant figure out is how to do these equations in algebra I dont know how to solve for an unkown variable or solve for zero, I know how to do it on paper but not on here.

    http://cn.iddqd.net/photos/sample2.jpg

    Same with this one:

    http://cn.iddqd.net/photos/sample.jpg

    and the APR calculator (the second half of it):

    http://cn.iddqd.net/photos/sample3.jpg

    what i have done so far can be seen here:

    http://www.cn.iddqd.net

    I did some work on the interest calculator but no matter what i do it still calculates it incorrectly lol. I would really appreciate it if some1 could help me out or at least point me in the right direction, all my teacher told me was "look at the included math functions" which I did, but that didnt really help me all that much. Thanks in advance ^^

    EDIT* here is the code i have so far:
    Code:
    // This file includes all of my functions on the site
    2
    3//Tax Functions
    //this is the one that woks!
    4 function monthlypaymentcalc() {
    5 var loan = $('loanamount').value;
    6 var rate = $('intrestrate').value;
    7 var months = $('monthnum').value;
    8 rate = rate / 1200;
    9 var loanrate = loan * rate;
    10 rate = rate + 1;
    11 rate = Math.pow(rate,months);
    12 var bottomrate = rate - 1;
    13 var toprate = rate * loanrate;
    14 var monthlypayment = toprate / bottomrate;
    15 monthlypayment = Math.round(monthlypayment);
    16 alert ("You will be required to pay $" + monthlypayment + " a Month on this loan.");
    17}
    //This is the one that doesnt work... right
    18function intrestratecalc() {
    19 var loan = $('loanamount2').value;
    20 var monpay = $('monthlypay').value;
    21 var months = $('monthnum2').value;
    22 var topnum = months * monpay - loan;
    23 var topnum = topnum * 2;
    24 var bottomnum = months * loan;
    25 var intrestrate = topnum / bottomnum;
    26 alert ("Your Intrest Rate will be " + intrestrate +"%.");
    27}
    //I got confused on this one
    28function numberofmonths() {
    29 var loan = $('loanamount3').value;
    30 var monpay = $('monthlypay2').value;
    31 var months = $('intrestrate2').value;
    32 alert ("Your Intrest Rate will be " + intrestrate +"%.");
    33}
    34document.observe("dom:loaded", function()
    35{
    //just my observes
    36 $('monthlypayments').observe("submit", monthlypaymentcalc.bind());
    37 $('intrestcalc').observe("submit",intrestratecalc.bind());
    38 $('numofmonths').observe("submit",numberofmonths.bind());
    39});
    I thought i should point out that I am using Prototype
    Last edited by Lanternkami; 03-13-2009 at 03:10 AM. Reason: Added Code

  • #2
    Senior Coder rangana's Avatar
    Join Date
    Feb 2008
    Location
    Cebu City, Philippines
    Posts
    1,752
    Thanks
    65
    Thanked 372 Times in 365 Posts
    Please replace your "functions.js" with this instead:
    Code:
    // This file includes all of my functions on the site
    
    //Tax Functions
    function monthlypaymentcalc() {
    	var loan = stripComma($('loanamount').value);
    	var rate = stripComma($('intrestrate').value);
    	var months = stripComma($('monthnum').value);
    	rate = Number(rate) / 1200;
    	var loanrate = Number(loan) * rate;
    	rate = rate + 1;
    	rate = Math.pow(rate,Number(months));
    	var bottomrate = rate - 1;
    	var toprate = rate * loanrate;
    	var monthlypayment = toprate / bottomrate;
    	monthlypayment = Math.round(monthlypayment);	
    	alert (isNaN(monthlypayment)?'Your monthly payment couldn\'t be computed':
    		"You will be required to pay $" + monthlypayment + " a Month on this loan.");	
    }
    function stripComma(val) {
    	return val.replace(/[,\s]/gi,'');
    }
    function intrestratecalc() {
    	var loan = stripComma($('loanamount2').value);
    	var monpay = stripComma($('monthlypay').value);
    	var months = stripComma($('monthnum2').value);
    	var topnum = Number(months) * Number(monpay) - Number(loan);
    	var topnum = topnum * 2;
    	var bottomnum = months * loan;
    	var intrestrate = topnum / bottomnum;
    	alert (isNaN(intrestrate)?'Your interest rate couldn\'t be computed':
    		"Your Intrest Rate will be " + intrestrate +"%.");
    }
    function numberofmonths() {
    	var loan = stripComma($('loanamount3').value);
    	var monpay = stripComma($('monthlypay2').value);
    	var months = stripComma($('intrestrate2').value);
    	alert (isNaN(intrestrate)?'Your interest rate couldn\'t be computed':
    		"Your Intrest Rate will be " + intrestrate +"%.");
    }
    document.observe("dom:loaded", function()
    {
    	$('monthlypayments').observe("submit", monthlypaymentcalc.bind());
    	$('intrestcalc').observe("submit",intrestratecalc.bind());
    	$('numofmonths').observe("submit",numberofmonths.bind());
    });
    The changes I've done are:
    • The textbox's values are STRING, and so you can't perform any math functions with that - you need to convert it either integer (parseInt()), float (parseFloat()), or Number().
    • I've added stripComma() function to remove commas and/or spaces from the textbox value before we do any computation:
      Code:
      function stripComma(val) {
      	return val.replace(/[,\s]/gi,'');
      }
    • When the result is not a number (NaN), another message appears instead.


    Hope that helps.
    Learn how to javascript at 02geek

    The more you learn, the more you'll realize there's much more to learn
    Ray.ph

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,178
    Thanks
    75
    Thanked 4,339 Times in 4,305 Posts
    Here's my own version of a simple loan calculator.

    Did it back in 1998 or so, as an entry into a "5KB Web Page" coding contest. That is, the ENTIRE web page had to fit in 5KB. Which this does pretty handily.

    http://www.juncojunction.com/5k/LoanCalculator.html

  • #4
    New to the CF scene
    Join Date
    Mar 2009
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Thx

    KK that might have been the issue I was having lol, I'm gonna take a look at your example and I'll add the StripComma(); to the rest of my calculators and make sure I convert them to numbers first, that could have been part of my problem, thx for the help everyone!

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,178
    Thanks
    75
    Thanked 4,339 Times in 4,305 Posts
    Did you read HOW to solve the calculation for interest rate???

    You can *NOT* do it by simply solving a single formula.

    As that page http://cn.iddqd.net/photos/sample3.jpg says , "the APR is calculated iteratively ... using the Newton-Raphson method."

    In other words, you guesstimate and then, depending on whether your guess is high or low, you adjust the guesstimate up or down and try again...and you keep doing it until you have the desired accuracy.

    So the only one you have right (I *think* it is right?) is the Monthly Payment calculation.

    p.s.: Notice how ancient my JS code is? Vintage 1998? Yet it still works today. Makes me wonder why we need all this other stuff.

    p.p.s.: Not sure why rangana just gave you back the same code, with no actual fixes. And not sure why he did the strip the way he did. I would have used:
    Code:
    function getValue(fld)
    {
        fld.value = fld.value.replace( /[^\d\.]/g, "" );
        return parseFloat( fld.value );
    }
    in place of stripCommas.

    Why wait until the calculations to find out that some value isNaN??

    But I admit that's my own preferred style.

  • #6
    Senior Coder rangana's Avatar
    Join Date
    Feb 2008
    Location
    Cebu City, Philippines
    Posts
    1,752
    Thanks
    65
    Thanked 372 Times in 365 Posts
    Old Pedant,

    I didn't gave the same function, if you'll take a look, I've converted textbox's values to number.

    For the regEx, I prefer a function to remove all of the unwanted strings than appending it as what you did, but as you said... personal preference though.

    ...but if I were to change the RegEx, I would have removed the case-insensitivity modifier.

    For the formula, I wish my algebra is good enough for me to comprehend the expected output
    Learn how to javascript at 02geek

    The more you learn, the more you'll realize there's much more to learn
    Ray.ph

  • #7
    New to the CF scene
    Join Date
    Mar 2009
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Yeah i read how to do it I just didn't understand it lol. I couldn't work how to make JavaScript solve for X, on some of the equations the formula requires you to use the unknown value in the formula. That is the part I was having the issues with. Right now I'm trying to do it out on paper and see If i can work it out that way, I'll get there sooner or later, I'm Probably just doing something stupid that I could easily fix.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,178
    Thanks
    75
    Thanked 4,339 Times in 4,305 Posts
    LOL! Well, so far as I know, the APR calc is the only one that needs to do as you said.

    If you look at my code, I do this:
    Code:
    function apr(){if(!fC(2))return;
    	incr=(test=50.0/tw)/2;var pv;
    	while(incr>0.00004/tw){
    		pv=V[1]*fF(test);
    		if (pv<V[0])test-=incr;else test+=incr;
    		incr/=2.0;}
    	if((test*=tw)<0.01||test>99.9)frm.APR.value = "--invalid--";
    	else{frm.APR.value=V[2]=fM(test);fA();}}
    That's ugly as pigsnot because I was trying to make it fit in those silly 5K bytes, so let's expand it. For some of it I'll just paraphrase the actual code you would use:
    Code:
    function apr()
    {
        // if(!fC(2))return;
        if(user did not supply PresentValue, Payment, and NumberOfMonths ) 
              return; // my code already has given a nasty alert
    
        // incr=(test=50.0/tw)/2;var pv;
        var test = 50.0 / 12*100; // 50% APR expressed as fraction per month
        var incr = test / 2; // the increment we adjust test by starts at half that
        var pv;  // Present Value from formula
    
        // we loop until the increment, expressed as an APR, is <= 0.000004%
       // (pretty damned accurate)
        while( incr > 0.00004/tw )
        {
            // fF is defined as: 
            // function fF(i){return(1-Math.pow(1+i,-NumberOFMonths*12))/i;}
            // I think you can recognize that from the equation you showed
            // So what we are doing is getting what the present value WOULD BE
            // given the current Payment, NumberOFMonths, and our test interest rate
            pv = payment * fF( test );
    
            // if our calculated pv is less than the value entered by the user...
            if ( pv < PresentValue ) 
                 test -= incr; // then our test interest rate was too high
            else
                 test+=incr; // otherwise it was too low
    
            incr /= 2.0; // and we make the increment half it's previous value
    
        } // end of loop waiting for the increment to get really tiny
    
        // if the calculated APR is not between 0.01 and 99.9, then
        // presumably the numbers given by the user are impossible
        // (well, you COULD have a 0 APR or even a 150% APR, but
        //  I opted to put reasonable limits on the values...and the iteration
        //  can't return a value of >= 100% in any case, as coded)
        if( (test *= tw )<0.01 || test > 99.9 )
            frm.APR.value = "--invalid--"; // meaning bad input numbers
        else
        {
            frm.APR.value = fM(test); // fM meant "format as Money" (before toFixed added to JS)
            fA(); // if requested, this writes out amortization schedule in popup
        }
    }
    Does that help you adapt it for your code??


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •