0

I have a text field with type='text' and I am trying to format the text with commas. Example: 500000000 would become 500,000,000.

I have the following code:

function addComma(values) {
   values.value = values.value.replace(",", "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

if (document.getElementById("values"))
    payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">

However, it's printing 5,000,0,0,0,000 and the formatting is off for some reason. I also tried .toLocaleString(), but that doesn't seem to work either. What am I doing wrong here?

I was referred to a few other posts on Stack Overflow, but nothing seems to work out.

Nissa
  • 4,636
  • 8
  • 29
  • 37
ace23
  • 142
  • 1
  • 16

4 Answers4

1

function addComma(values) {
  const v = values.value && new Number(values.value.replace(/,/g,''));
   values.value = v.toLocaleString();
}

if (document.getElementById("values"))
         payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
dsych
  • 754
  • 7
  • 13
1

You can do this by converting the number to a string, then manually iterating over each character and find places where a comma is needed.

function formatNumber(number) {
  var str = number.toString();
  var offset = str.length % 3;
  var newStr = '';
  for (var i = 0; i < str.length; i++) {
    if (i > 0 && i % 3 === offset) {
      newStr += ',';
    }
    newStr += str[i];
  }
  console.log(str, '=>', newStr);
}

formatNumber(5);
formatNumber(50);
formatNumber(500);
formatNumber(5000);
formatNumber(50000);
formatNumber(500000);
formatNumber(5000000);
sasensi
  • 4,610
  • 10
  • 35
0

I'd recommend using a change event rather than a keyup event as change will only update the value when the input is no longer the focus. If you use keyup the code will try and reinterpret the new string you add back to the input as a number and throw an error.

Here's the code using toLocaleString (just press tab after adding the number as if to move to the next input box):

const values = document.querySelector('#values');
values.addEventListener('change', handleChange, false);

function handleChange(e) {
  const value = Number(e.target.value);
  const formatted = value.toLocaleString();
  values.value = formatted;
}
<input id="values" type="text">
Andy
  • 61,948
  • 13
  • 68
  • 95
0

The other answers posted before this one using the input field are ok to show how it works, but they are bugged as soon as you enter a new number when it has formatted to a string using toLocaleString(). For that reason I added the toNumber() function to be complete. In the example below I preform the following steps:

When user fills in a number in the input field and leaves the input field: Call toString(e) and make from the entered number a formatted string.

If the user again selects the input field, call toNumber(e) and format it back to a number.

This makes sure you won't get NaN when reselecting or will become completely unusable.

The NaN property represents "Not-a-Number" value. This property indicates that a value is not a legal number.

It is still possible to add text in it, this will result in NaN as text cannot be formatted to a number. This could be filtered out in the toString(e) when necessary. I did this in the example below by adding if (formatted !== 'NaN') {} Only when it's not NaN it will set the value to the new formatted number. Else it won't do anything. Please note: a number with dots is a string in this case so wont work either.

const values = document.querySelector('#values');
values.addEventListener('click', toNumber, false);
values.addEventListener('focusout', toString, false);

function toNumber(e) {
  const value = e.target.value;
  const unformatted = value.replace(/\D/g,'');
  values.value = unformatted;
}

function toString(e) {
  const value = Number(e.target.value);
  const formatted = value.toLocaleString();
  if (formatted !== 'NaN') {
     values.value = formatted; 
  }
}
<input id="values" type="text">

To fix that, you can also remove my addition and add a filter before the toString(e) does it's thing and filter the dots, text etc. so only the numbers remain.

JeroenE
  • 603
  • 7
  • 22