0

Is it possible to add a decimal on a number input, as a user types?

I have the below input:

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

And I want it to look like the below as I type: enter image description here

I've tried to set the input.value and wrap it in formatter.format(), using the below, but I get a parsing error. Because of the $ sign and it being a number input, I'm guessing.

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

Is there anyway to do this?

Matt Davis
  • 47
  • 1
  • 9
  • https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#allowing_decimal_values – kol Aug 12 '21 at 19:18
  • Does this answer your question? [Allow 2 decimal places in ](https://stackoverflow.com/questions/34057595/allow-2-decimal-places-in-input-type-number) – SuperDJ Aug 12 '21 at 19:20
  • I've already found and tried this and it doesn't work. The placeholder also needs to be 0 and the decimal to be added as the user types and adds more numbers. I've also removed the spin button, due to the design it needs to not have them. – Matt Davis Aug 12 '21 at 19:25

1 Answers1

1

Use regex to remove non digits, then add the decimal using string function.

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"
/>
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116