0

How to add commas to numbers, presently I'm producing an output like this 1,2,3,4,5,6,7,890 - trying to have a result that outputs the following 1,234,567,890 - using keyup which might cause issues, please advise

numberWithCommas : function () {
  var goal = $("#foo");
  goal.val(goal.val().toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
},

Update:I found that replace(/\B(?=(\d{3})+(?!\d))/g, ','); fixed the issue of too many commas

frostjohn
  • 9
  • 3
  • Why are you doing `toString()`? It is already a string. – putvande Nov 18 '13 at 19:08
  • Maybe this answer: http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript can help. Also you can take a look to: http://numeraljs.com/ – Diego Nov 18 '13 at 19:08
  • can somebody explain me this regexp? http://stackoverflow.com/q/20055932/57218 – Guilherme Nov 18 '13 at 19:17

1 Answers1

2

remove all the current commas, then insert new ones in the appropriate places :

numberWithCommas : function () {
  $("#foo").val(function(_,val) {
    return val.replace(/\,/g,'').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  });
},

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • your fiddle is not working. – Guilherme Nov 18 '13 at 19:14
  • @Guilherme - it's working just fine for me, doesn't the input display `1,234,567,890`. – adeneo Nov 18 '13 at 19:21
  • @adeneo Adding [an explanation](http://meta.stackexchange.com/questions/177757/are-answers-that-just-contain-a-regular-expression-pattern-really-good-answers) on how the regex works is greatly appreciated – HamZa Nov 18 '13 at 19:24
  • @HamZa - how the hell should I know how it works, I just got it from the OP's question, and to make it work you have to remove the commas first, as that regex inserts a comma between groups of three digits (that's what `\d{3}` is, three digits) and with the commas still there, there are no groups of three digits. If you'd like to know how a regex works, just test it -> https://www.debuggex.com/r/FnjqYRfPkHdNe5vg – adeneo Nov 18 '13 at 19:36
  • @adeneo lol easy don't get mad. It's just that someone posted [a question](http://stackoverflow.com/questions/20055932) referring to this question asking for explanation. I scrolled right away to your answer and didn't even notice that it's from the OP, my bad. So I posted a comment and then realised what's going on, I didn't want to delete my comment. Btw there is no need to escape a comma `/,/g` – HamZa Nov 18 '13 at 19:41
  • 1
    I wasn't mad, and I do have a general idea of what the regex does and how it's built up, but I didn't really look at it that closesly as it wasn't mine to begin with, I just noticed the groups of three digits, and realized it would only work if first removing the existing commas. – adeneo Nov 18 '13 at 19:45