jerrymouse
jerrymouse

Reputation: 17812

print number with comma as hundred separator

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?

Upvotes: 0

Views: 553

Answers (3)

amal jith
amal jith

Reputation: 67

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

Upvotes: 0

paddy
paddy

Reputation: 63481

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 =)

Upvotes: 3

Giberno
Giberno

Reputation: 1333

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))

Upvotes: 0

Related Questions