你好 SO 上的好人。
所以我在贷款计算器中有一个输入字段。在这里,我希望用户输入的输入值采用小数格式(例如,为了更容易区分 100000 和 1000000。)
我想用 JavaScript 来做这个“转换”,如果我可以这样称呼的话,我在 MDN 文档中找到了一些关于名为“Intl.NumberFormat”的对象构造函数的内容
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
然后我将以下内容粘贴到我自己的 JS 文件中,如下所示:
// Changes Loan Amount input to decimal format
document.getElementById("amount").addEventListener("input", function(){
new Intl.NumberFormat('en-CA', {style: "decimal"}).format(amount);
});
我的 HTML 看起来像这样:
<span class="input-group-text">$</span>
<input
type="text"
class="form-control"
id="amount"
placeholder="Loan Amount"
/>
所以我正在寻找的结果是让输入在用户输入时看起来像这样:
取而代之的是:
希望这很清楚。在此先感谢您的帮助。
最佳答案
您没有使用格式化文本更新输入字段:
document.getElementById("amount").addEventListener("input", function(){
document.getElementById("amount").value = new Intl.NumberFormat('en-CA', {style: "decimal"}).format(document.getElementById("amount").value);
});
但是,我认为您会希望从每次输入迭代中去除非数字字符,因此这可能更接近您想要的:
document.getElementById("amount").addEventListener("input", function(){
document.getElementById("amount").value = new Intl.NumberFormat('en-CA', {style: "decimal"}).format(document.getElementById("amount").value.match(/\d+/g).join(''));
});
关于javascript - 用小数格式化的输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55149009/