I am trying to create a loan calculator that uses commas to separate every third number. For example, $1,000,000.75.

Is there a way to display all of the input values like this, without compromising the actual calculation of numbers?

Right now, if a comma is entered in any of the inputs, than the calculated input (input that displays the calculation), throws an error (NaN). I am wondering if there is any way to do this using something such as PHP or JavaScript?

Here is a picture of a working example of my loan calculator:

enter image description here

Here is my full page code for the loan calculator:

<!doctype html>
<html>
<head>
<style>
body {
    font-family:arial,verdana,sans-serif;
}

img a {
    border:none;
}

img {
    border:none;
}

.bback {
    text-align:center;
    width:100%;
}

#image {
    width:84px;
    height:41px;
}

#stretchtable {
     width:60%;
     max-width:500px;
     min-width:200px;
}

.fontwhite {
    color:white;
    background-color:black;
    border:4px grey solid;
    padding:5px;
    text-align:left;
}
</style>
<meta charset="utf-8">
<title> ::: Loan Calculator</title>
</head>

<body bgcolor="#102540">


 <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;
 princ = princ.replace(',','');
 var myfloat = parseFloat(princ);
 var term  = document.calc.months.value;
 term = term.replace(',','');
 var myfloat1 = parseFloat(term);
 var intr   = document.calc.rate.value / 1200;
 intr = intr.replace(',','');
 var myfloat2 = parseFloat(intr);
 document.calc.pay.value = (myfloat * myfloat2 / (1 - (Math.pow(1/(1 + myfloat2), myfloat1)))).toFixed(2)

 }

// payment = principle * monthly interest/(1 - (1/(1+MonthlyInterest)*Months))

}

// -->
</script>

<script>
function trimDP(x, dp) {
    x = parseFloat(x);
    if (dp === 0)
        return Math.floor(x).toString();
    dp = Math.pow(10, dp || 2);
    return (Math.floor((x) * dp) / dp).toString();
}


window.addEventListener('load', function () {
    var nodes = document.querySelectorAll('.dp2'), i;
    function press(e) {
        var s = String.fromCharCode(e.keyCode);
        if (s === '.')
            if (this.value.indexOf('.') === -1)
                return; // permit typing `.`
        this.value = trimDP(this.value + s);
        e.preventDefault();
    };
    function change() {
        this.value = trimDP(this.value);
    }
    for (i = 0; i < nodes.length; ++i) {
        nodes[i].addEventListener('keypress', press);
        nodes[i].addEventListener('change', change);
    }
});
</script>

<div class="bback">
<h1 style="color:white;font-size:16px;">G.B.M. Trailer Service Ltd. Loan Calculator</h1>
<a href="index.html">
<img src="images/backbutton.png" alt="Back Button" id="image" title="Back"></a><br /><br />
<center>
<div class="fontwhite" style="width:60%;">
The results of this loan payment calculator are for comparison purposes only.
They will be a close approximation of actual loan
repayments if available at the terms entered, from a financial institution. This
is being
provided for you to plan your next loan application. To use, enter values
for the
Loan Amount, Number of Months for Loan, and the Interest Rate (e.g.
7.25), and
click the Calculate button. Clicking the Reset button will clear entered
values.
</div>
</center>
</div>
<p>
<center>
<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" onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black">Loan Length in Months</td><td bgcolor="black"
align=center><input type=text
name=months size=10 onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black">Interest Rate</td><td bgcolor="black" align=center><input
type=text name=rate
size=10 onkeyup="format(this)"></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" onkeyup="format(this)"></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>

<div style="width:60%;">
<font size=2 color=white>Enter only numeric values (no commas), using decimal points
where needed.<br>
Non-numeric values will cause errors.</font>
</center>
</div>

<p align="center"><font face="arial" size="-2">This free script provided by</font><br>
<font face="arial, helvetica" size="-2"><a href="http://javascriptkit.com">JavaScript
Kit</a></font></p>

</body>
</html>

I am looking for a solution to my problem, as I am not experienced with this type of code. Suggestions may only get me so far.

Thank you for any help. All help is greatly appreciated.

有帮助吗?

解决方案

Replace this:

var intr = document.calc.rate.value / 1200;

with this

var intr = (parseFloat(document.calc.rate.value) / 1200).toString()

For the adding commas bit, replace this:

document.calc.pay.value = (princ * intr / (1 - (Math.pow(1/(1 + intr), term)))).toFixed(2)

with this

document.calc.pay.value = (princ * intr / (1 - (Math.pow(1/(1 + intr), term)))).toFixed(2).toLocaleString()

there are other ways to do it, but this seems like the fastest way without introducing more functions. JavaScript gives us toLocaleString which should be your most flexible option.

其他提示

Before calculation simply use .replace(',','') to remove the commas. Then you need to cast it to to a float by using parseFloat(). Then when you go to display the numbers you can reformat it with commas if you would like.

var mystring = '10,000.12';
mystring = mystring.replace(',','');
var myfloat = parseFloat(mystring);

For adding the commas back in you can do something like this: How to print a number with commas as thousands separators in JavaScript

From that answer:

function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top