View Full Version : Need Help with JavaScript (Building a variety of calculators)

03-13-2009, 03:31 AM
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.


Same with this one:


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


what i have done so far can be seen here:


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 ^^ :confused:

EDIT* here is the code i have so far:

// This file includes all of my functions on the site
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.");
//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 +"%.");
//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 +"%.");
34document.observe("dom:loaded", function()
//just my observes
36 $('monthlypayments').observe("submit", monthlypaymentcalc.bind());
37 $('intrestcalc').observe("submit",intrestratecalc.bind());
38 $('numofmonths').observe("submit",numberofmonths.bind());

I thought i should point out that I am using Prototype

03-13-2009, 04:21 AM
Please replace your "functions.js" with this instead:

// 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());

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:

function stripComma(val) {
return val.replace(/[,\s]/gi,'');

When the result is not a number (NaN), another message appears instead.

Hope that helps.

Old Pedant
03-13-2009, 04:48 AM
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.


03-13-2009, 06:05 AM
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! :thumbsup:

Old Pedant
03-13-2009, 06:09 AM
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:

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.

03-13-2009, 06:14 AM
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 :p

03-13-2009, 06:35 AM
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.

Old Pedant
03-13-2009, 06:53 AM
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:

function apr(){if(!fC(2))return;
incr=(test=50.0/tw)/2;var pv;
if (pv<V[0])test-=incr;else test+=incr;
if((test*=tw)<0.01||test>99.9)frm.APR.value = "--invalid--";

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:

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
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
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??