如何在没有妥协计算器的情况下显示每三个数字后的逗号

时间:2014-04-10 19:24:57

标签: javascript php html input calculator

我正在尝试创建一个贷款计算器,使用逗号分隔每三个数字。例如,$ 1,000,000.75。

有没有办法像这样显示所有输入值,而不会影响数字的实际计算?

现在,如果在任何输入中输入逗号而不是计算输入(显示计算的输入),则会引发错误(NaN)。我想知道是否有任何方法可以使用PHP或JavaScript之类的东西来做到这一点?

以下是我的贷款计算器的工作示例图片:

enter image description here

这是我的贷款计算器的完整页面代码:

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

我正在寻找解决我问题的方法,因为我对这类代码没有经验。建议可能只会让我到目前为止。

感谢您的帮助。非常感谢所有帮助。

2 个答案:

答案 0 :(得分:1)

替换它:

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

用这个

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

对于添加逗号位,请替换为:

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

用这个

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

还有其他方法可以做到这一点,但这似乎是没有引入更多功能的最快方法。 JavaScript为我们提供了LocaleString,它应该是您最灵活的选择。

答案 1 :(得分:0)

在计算之前,只需使用.replace(',','')删除逗号即可。然后,您需要使用parseFloat()将其强制转换为浮点数。然后当你去显示数字时,如果你愿意,可以用逗号重新格式化。

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

要添加逗号,您可以执行以下操作: How to print a number with commas as thousands separators in JavaScript

从那个答案:

function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}