|
Interesting JavaScript code example: finance calculator
I've been building a financial calculator that lets you enter a monthly payment, an interest rate level and an overall debt level, then tells you how long it'll take to pay off the loan and how much interest you'll end up paying. It's fairly self-explanatory, I think, and interesting to read.
First off, here's the JavaScript:
<script type="text/javascript">
<!--
// Script written by Dave Taylor based on some math suggested by
// Bennett Haselton @ Peacefire.org. Thanks Bennett!
function centNotation(value)
{
// return the value in normalized dollars.cents notation
dollars = Math.floor(value); // chop floating point portion
cents = Math.floor((value % 1) * 100); // and chop everything else
if (cents < 10) cents = "" + cents + "0";
return(dollars + "." + cents);
}
function validInt(value)
{
// return true if it's digits or decimal point-only, false otherwise.
for (var i=0; i < value.length; i++) {
var c = value.charAt(i);
if ((c < '0' || c > '9') && c != '.') {
alert("There's a problem: all values herein must " +
"be numbers only, and " + value + " has an unacceptable character " +
"'" + c + "'");
return(false);
}
}
return(true);
}
function myPaymentCalc()
{
// calculate the number of payments and total payments for a simple loan given
// the interest, monthly payment and principal of the loan.
var interestRate = document.debtcalc.interest.value,
monthlyPayment = document.debtcalc.monthlypayment.value,
principal = document.debtcalc.principal.value,
accumulatingInterest = 1;
if (! validInt(interestRate) || ! validInt(monthlyPayment) ||
! validInt(principal))
return(false);
if (interestRate == 0 || monthlyPayment == 0 || principal == 0) {
alert("You need to specify your monthly payment, credit card " +
"interest rate and current debt amount before I can calculate " +
"how long it'll take for you to pay off your debt.");
return(false);
}
interestRate = (interestRate > 1)? interestRate / 100.0 : interestRate;
monthlyInterestRate = interestRate / 12;
if (principal * monthlyInterestRate > monthlyPayment) {
monthlyrate = "$" + centNotation(principal * monthlyInterestRate);
permonthPayment = "$" + centNotation(monthlyPayment);
alert("You've got a fundamental problem: your monthly payment of " +
permonthPayment + " is less than the interest added each month " +
"(which is " + monthlyrate + ") and you will never " +
"pay off this debt. It might be a good time to call your creditors.");
return(false);
}
interimVal1 = monthlyPayment - (monthlyInterestRate * principal)
numberOfPayments = (Math.log(monthlyPayment) - Math.log(interimVal1)) /
Math.log(1+monthlyInterestRate);
numberOfPayments = Math.ceil(numberOfPayments);
interimVal2 = Math.pow((monthlyInterestRate+1), (numberOfPayments-1));
remaining = (principal * interimVal2) -
(monthlyPayment/monthlyInterestRate) * (interimVal2 - 1);
totalPayment = monthlyPayment *(numberOfPayments-1) + remaining;
// clean up the display format to make it attractive...
payments = numberOfPayments;
totalpayment = "$" + centNotation(totalPayment);
interestPaid = "$" + centNotation(totalPayment-principal);
alert("Given these figures, you'll end up having " + payments +
" payments and pay a total of " + totalpayment + ", of which " +
interestPaid + " is interest.");
}
// -->
</script>
Did I mention that it's a lot of JavaScript? :-)
The other part of this is the form itself, which actually ends up being fairly short by comparison: <form id="debtcalc" name="debtcalc" action="#"> <div style="border:1px solid #669; padding:3px;font-size:85%;"> <div style="font-size:110%;font-weight:bold;">How long will it take for you to pay off those holiday bills?</div> Monthly payment: <input type="text" size="6" name="monthlypayment" /> interest rate (APR): <input type="text" name="interest" size="5" /> and amount owed: <input type="text" name="principal" size="9" /> then <input type="button" value=" solve " onclick="myPaymentCalc()" style="font-size: 80%;background-color: #CFC" /> </div> </form>So, want to see it in use? Go to RealLifeDebt.com and you'll find it on the home page.
Categorized:
CGI Scripts and Web Site Programming
(Article 3670,
Written by Dave Taylor)
Tagged: Previous: A cautionary tale about xhtml validators Next: New book: "Linux for Dummies, 5th Ed." released Subscribe!
OMG, I can't believe you call yourself a 'guru'. centNotation() has an error in the line: if (cents < 10) cents = "" + cents + "0"; Remind me not to get you to do my tax. The script has no effect in my browser when I go to RealLifeDebt.com because it was included as follows (this should be in the head rather than the body, by the way): [script src="calculator.js" type="text/css"][/script] After replacing "text/css" with "text/javascript" it worked fine. Posted by: Jason Boyle at July 13, 2007 1:27 AMThis line is missing from my comment above: <script src="calculator.js" type="text/css"></script> Posted by: Jason Boyle at July 13, 2007 1:30 AMHi: UM.. this code DOES not round up.. but down.. lol if you use it you will miss 1 cent on every total. Posted by: hmm at February 27, 2011 12:25 AMI' trying to create a javascript image uploader,so that people can upload their images on my website and preview them first.however the image uploader code is only working on IE, it doesn't work on google chrome. Can you please send me a code that works on google chrome? N.B. If you can send me the code please send it on my e-mail as well so I can retreive it on my phone: coolelio12@hotmail.com Posted by: leo at July 20, 2011 4:07 AMI have something to say, now that you mention it, but ...
I do have a comment, now that you mention it!
|
Recommended
Recent Entries
Search
I Need Help!
Apple iPad Help
Articles and Reviews Auctions and Online Shopping Blogs and RSS Feeds Building Web Site Traffic Business and Management CGI Scripts and Web Site Programming Computer and Internet Basics d) None of the Above Facebook Help Google Plus Help HTML and CSS Industry News and Trade Shows iPhone and Cell Phone Help iPod, Sony PSP and MP3 Player Help Mac OS X Help Pay Per Click (PPC) Advertising Search Engine Optimization (SEO) Shell Script Programming Tech Support Video Help The Writing Business Twitter, LinkedIn and Social Network Help Unix and Linux Help Video Game Tips and Help Windows PC Help WordPress Help |