0

I am trying to format a users input as a currency. I have an input field where a user would type how much they want to pay. As they type the number I would like it to start formatting as they type. So formatting wise I would like it to look like:

$1,200.23

Zachary
  • 300
  • 3
  • 11

1 Answers1

1

You can use Intl NumberFormat method with currency set to USD

const input = document.querySelector("#currency");
const [label] = input.labels;
const formatter = new Intl.NumberFormat("en-US", {style: "currency", currency: "USD"});

input.addEventListener("input", e => {
  label.textContent = formatter.format(input.value)
})
<input type="number" id="currency">
<label for="currency"></label>
guest271314
  • 1
  • 15
  • 104
  • 177
  • This is so close to what I am looking for. I just would love the input to update accordingly. Thank you! – Zachary Feb 15 '19 at 19:18
  • 1
    @Zachary You can change `type` of `` to `"text"` and use `change` event instead of `input` event with `input.value = formatter.format(input.value.replace(/[$]+/, ""))` – guest271314 Feb 15 '19 at 19:24
  • @Zachary Using `input` event `input.addEventListener("input", e => { if (!/[0-9.]+/.test(e.data)) { e.preventDefault(); } else { input.value = formatter.format(input.value.replace(/[$]+/, ""))` – guest271314 Feb 15 '19 at 19:34