0

I have a number like "7847258998" which I want to print with hundred comma separator in javascript. The result should be:

7,84,72,58,998

i.e the first three digits from right should be grouped together. Remaining digits grouped in chunks of 2. I tried with following:

"7847258998".replace(/\B(?=(\d{3})+(\d{2})+(?!\d))/g, ",")

But it returns: 7,8,4,72,58998. What is the right expression?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
jerrymouse
  • 16,964
  • 16
  • 76
  • 97
  • Made it work. I Separated last 3 digits and applied comma on the remaining using `(/\B(?=(\d{2})+(?!\d))/g, ",")` – jerrymouse Oct 07 '12 at 13:47

3 Answers3

3

Try this:

"7847258998".replace(/\B(?=(\d{2})*(\d{3})$)/g, ",");

I match the end of the string in the lookahead so that I'm always looking for something sane. Otherwise just about anything matches.

Tested on inputs length 1-10.. Enough to decide that it probably works. Pretty inefficient way to do it though, as for each character you have to parse the rest of the string.

But you did ask for a regular expression that does the job =)

paddy
  • 60,864
  • 6
  • 61
  • 103
  • 1
    +1. As a small improvement, you might change `\B` to `\d`, and the replacement-string from `","` to `"$1,"`. That way, it will only insert a comma after a digit specifically (and not after a letter or underscore). – ruakh Oct 07 '12 at 13:59
  • Not sure if its that inefficient, as it is voted as the best answer here http://stackoverflow.com/questions/2901102/how-to-print-number-with-commas-as-thousands-separators-in-javascript – jerrymouse Oct 07 '12 at 14:01
0
function commafy(num)
{  
   num  =  num+"";  
   var  re=/(-?\d+)(\d{3})/  
   while(re.test(num))
   {  
     num=num.replace(re,"$1,$2")  
   }  
   return  num;  
}
function  commafyback(num)
{  
   var x = num.split(',');
   return parseFloat(x.join(""));
} 
alert(commafy(7847258998))
Giberno
  • 1,323
  • 4
  • 17
  • 31
  • 1
    That gives the wrong answer: it gives `7,847,258,998`, but the OP wants `7,84,72,58,998`. (See http://en.wikipedia.org/wiki/South_Asian_numbering_system.) – ruakh Oct 07 '12 at 13:18
0

You can convert the number to a locale string using the en-IN locale.

(7847258998).toLocaleString("en-IN")

If the value is a string, convert it to a number first:

const value = "7847258998"
Number(value).toLocaleString("en-IN")

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

amal jith
  • 57
  • 5