I am trying to create a loan calculator that will give me the calculated monthly payment in a number with a maximum of two decimal places. I am currently using the following formula, but it gives me more than two decimal places (see the image below.):
<script language="JavaScript">
<!--
function showpay() {
if ((document.calc.loan.value == null || document.calc.loan.value.length == 0) ||
(document.calc.months.value == null || document.calc.months.value.length == 0)
||
(document.calc.rate.value == null || document.calc.rate.value.length == 0))
{ document.calc.pay.value = "Incomplete data";
}
else
{
var princ = document.calc.loan.value;
var term = document.calc.months.value;
var intr = document.calc.rate.value / 1200;
document.calc.pay.value = princ * intr / (1 - (Math.pow(1/(1 + intr), term)));
}
// payment = principle * monthly interest/(1 - (1/(1+MonthlyInterest)*Months))
}
// -->
</script>
Here is the HTML for my loan calculator:
<form name=calc method=POST>
<div style="color:white; font-weight:bold; border:4px grey outset; padding:0px; margin:0px;" id="stretchtable">
<table width="100%" border="1" style="border:1px outset grey">
<tr><th bgcolor="black" width=50%><font color=white>Description</font></th>
<th bgcolor="black" width=50%><font color=white>Data Entry</font></th></tr>
<tr><td bgcolor="black">Loan Amount</td><td bgcolor="black" align=center><input
type=text name=loan
size=10 class="dp2"></td></tr>
<tr><td bgcolor="black">Loan Length in Months</td><td bgcolor="black"
align=center><input type=text
name=months size=10></td></tr>
<tr><td bgcolor="black">Interest Rate</td><td bgcolor="black" align=center><input
type=text name=rate
size=10></td></tr>
<tr><td bgcolor="black">Monthly Payment</td><td bgcolor="black"
align=center><em>Calculated</em> <input
type=text name=pay size=10 class="dp2"></td></tr>
<tr><td bgcolor="black"align=center><input type=button onClick='showpay()'
value=Calculate></td><td bgcolor="black" align=center><input type=reset
value=Reset></td></tr>
</table>
</div>
</form>
When the calculated monthly payment appears, it appears in many decimal places. I would like this to be limited to only 2 decimal places, and for those decimal places to be rounded to the nearest hundredth. I believe this can be achieved through PHP or JavaScript.
Note: I am looking for a direct solution to my problem, not suggestions/hints.
For example:
If I had 2.489999
as the monthly calculated payment, than the new code would make it 2.49
.
Here is a picture of what my loan calculator looks like:
Thank you for any help. All help is greatly appreciated.