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