1

I'm making a basic tax calculation app using Javascript. I want to put a number into an input, then have it display in the input with commas e.g input 100000 display 100,000. I need to then use this value for the calculations, so it has to be converted back to an integer.

I have the first part to convert, but I'm not sure the best way to convert back to actually use in the calculations.

let updateNumber = function (inputValue) {
  let newValue = Intl.NumberFormat().format(this.value);

  income.value = newValue;
};

income.addEventListener("change", updateNumber);

Hopefully, that makes sense. This is my first post.

bradmeyn
  • 47
  • 3
  • `parseInt(newValue.replace(",",""), 10);` – Scott Marcus Jul 29 '20 at 21:01
  • Does this answer your question? [How can I parse a string with a comma thousand separator to a number?](https://stackoverflow.com/questions/11665884/how-can-i-parse-a-string-with-a-comma-thousand-separator-to-a-number) – Heretic Monkey Jul 29 '20 at 21:02
  • @ScottMarcus That returns `100` for `'100,000'`... – Heretic Monkey Jul 29 '20 at 21:03
  • Why don't you work with `this.value`? – Unmitigated Jul 29 '20 at 21:05
  • Does this answer your question? [Is there a way to reverse the formatting by Intl.NumberFormat in JavaScript](https://stackoverflow.com/questions/29255843/is-there-a-way-to-reverse-the-formatting-by-intl-numberformat-in-javascript) – James Jul 29 '20 at 21:06
  • 1
    This is an interesting question but still why not just remember the old value instead of trying to reverse engineer the new one? – GirkovArpa Jul 29 '20 at 21:21

1 Answers1

0

You can use the unary plus operator to convert the input's value to a number before replacing it.

Example:

let updateNumber = function (inputValue) {
  let newValue = Intl.NumberFormat().format(this.value);
  let num = +this.value;
  income.value = newValue;
  console.log(num * 2);
};

document.querySelector('#income').addEventListener("change", updateNumber);
<input id="income">
Unmitigated
  • 76,500
  • 11
  • 62
  • 80