首页 > 解决方案 > 用小数格式化的输入值

问题描述

你好,好人。

所以我在贷款计算器中有一个输入字段。在这里,我希望用户输入的输入值用小数格式化(例如,为了更容易区分 100000 和 1000000。)

如果我可以这样称呼它,我想使用 JavaScript 来进行这种“转换”,并且我在 MDN Docs 中找到了一些关于名为“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"
                  />

所以我正在寻找的结果是让用户输入时的输入看起来像这样:

通缉_结果

而不是这个:

在此处输入图像描述

希望这很清楚。提前感谢您的帮助。

标签: javascriptformsinput

解决方案


您没有使用格式化文本更新输入字段:

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(''));
});

推荐阅读