数字输入的小数点

Decimal point on number input

是否可以在用户键入时在数字输入上添加小数?

我有以下输入:

     <div class="form-control">
          <label for="bill">Bill</label>
          <input
            type="number"
            id="bill"
            name="bill"
            placeholder="0"
            maxlength="6"
          />

我希望它在我输入时看起来像下面这样:

我尝试使用以下设置 input.value 并将其包装在 formatter.format() 中,但出现解析错误。因为 $ 符号和它是一个数字输入,我猜。

let formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD', });

有办法吗?

使用正则表达式删除非数字,然后使用字符串函数添加小数。

document.getElementById('bill').addEventListener('input', function(){
  if(this.value.length > 2){
    var val = this.value.replace(/[^\d]/, '');
    val = val.substr(0, val.length-2)+"."+val.substr(-2);
    this.value = val;
  }
});
<input
  type="number"
  id="bill"
  name="bill"
  placeholder="0"
  maxlength="6"
/>