1

I'm trying my mimic the comma insertion for input type='number' in FireFox since it doesn't support it yet. Naively it works in Chrome. I got my regex to work...just not in the right order, I need to reverse it.

http://jsfiddle.net/hCTDV/2/

You can see that it will format the number as 123,4 instead of 1,234. I tried 'reverse()' but I can't get that to work, Firefox states it's not a function.

If somebody could adjust my regex so it properly performs the task I want that will be great, otherwise running it in reverse might do.

ngen
  • 8,816
  • 2
  • 18
  • 15
  • .reverse is an method of Array object.. – The Mask Jul 07 '11 at 20:10
  • You should be aware that many cultures do not represent numbers this way. See http://en.wikipedia.org/wiki/Myriad for discussions of how Chinese numbering systems tend to group digits by 4, and European numbers are often written with dots separating (1e6 === 1.000.000). http://stackoverflow.com/questions/1068284/format-numbers-in-javascript has more info on number formatting. – Mike Samuel Jul 07 '11 at 20:17
  • @Mike Samuel: I am aware of that and thanks for brining that up. This will be used only in the USA internally in our company. – ngen Jul 07 '11 at 20:24

3 Answers3

1

You can use something like:

var str = "foo 123456789.22 bar";    
str = str.replace(/\d(?=(?:\d{3})+(?!\d))/g, '$&,');

http://jsfiddle.net/Ar3Qv/

Note that this will only work as long as the decimal part is no more than 3 digits, else it will add , in the decimal part too.

Qtax
  • 33,241
  • 9
  • 83
  • 121
1

Try this method:

  $('input').keyup(function(){
    var $this = $(this);
    var num = $this.val().replace(/,/g, '');
    $this.val(num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
  });

It seems a bit simpler and appears to work - http://jsfiddle.net/hCTDV/3/

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
  • Miessier: I do like that method better. Thanks. I accepted your answer but do appreciate the help from others. I didn't ask for Chrome but I just noticed it's affected. After the 4th keyup event, Chrome will clear the input. If I set the input type to text, it's fine. Any ideas? – ngen Jul 07 '11 at 20:22
  • This may be irrelevant to the OP, but this code doesn't work for numbers with decimal points. `"1000000.00001".replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")` `===` `"1,000,000.00,001"` so the integer part is formatted correctly but the fraction portion is not. – Mike Samuel Jul 07 '11 at 20:33
0

what you can do you can reverse string then apply regex to it then reverse it again, solution is below:

 $(this).val( $(this).val().replace(".","").split("").reverse().join("").replace(/([0-9]{3}(?=([0-9])))/g, "$1,").split(""),reverse().join("");

I hope this helps

Senad Meškin
  • 13,597
  • 4
  • 37
  • 55