0

I have spent time looking through each of the proposed solutions to the problem of adjusting user input strings as they type to format a large number to have comma separators:

9999999999 --> 9,999,999,999 and so on.

There are several discussions here on stack overflow:

How to print a number with commas as thousands separators in JavaScript

Adding comma as thousands separator (javascript) - output being deleted instead

and many more related queries, I've tested those that I could find, and they worked well for numbers up to a power of 4 or 5, eg 12,345 comes out nicely,

But larger numbers end up with far too many commas:

1,,,,,0,,,0,,,000

for example is the output of the code I currently have implemented. (It also registers backspace as a key stroke, so when I backspace three times it adds a comma...)

function numberWithCommas(n){
    var s=n.split('.')[1];
    (s) ? s="."+s : s="";
    n=n.split('.')[0]
    while(n.length>3){
        s=","+n.substr(n.length-3,3)+s;
        n=n.substr(0,n.length-3)
    }
    return n+s
}

and then on the input:

onkeyup="this.value=numberWithCommas(this.value);"

Am I using the function incorrectly? Or is it simply not viable for larger numbers. Is there a way it can be adjusted to work for any size of number?

Thanks in advance

Community
  • 1
  • 1
Gideon
  • 1,878
  • 4
  • 40
  • 71

1 Answers1

1

You are just adding comas to a value which already as commas after the first iteration... You should just reset the commas at the beginning of your function numberWithCommas:

n = n.replace(/,/g, "");
Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
  • So simple, so many hours of me trying to figure this out >_< one day I will understand enough to not have to beat my face against a problem for so long :) Thanks very much - works perfectly. – Gideon Nov 29 '12 at 22:33