3

I want to format numbers. I have seen some of the regex expression example to insert comma in number string. All of them check 3 digits in a row and then insert comma in number. But i want something like this:

122 as 122
1234 as 1,234
12345 as 12,345
1723456 as 17,23,456
7123456789.56742 as 7,12,34,56,789.56742

I am very new to regex expression. Please help me how to display the number as the above. I have tried the below method. This always checks for 3 digits and then add comma.

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

But i want comma every 2 digits except for the last 3 digits before the decimals as shown above.

user850234
  • 3,373
  • 15
  • 49
  • 83
  • u want answer in regex or javascript.. or tell what u have tried?? – Javascript Coder May 30 '12 at 05:42
  • @Learner : In which ever way it is simple. – user850234 May 30 '12 at 05:43
  • @Learner What do you mean "in regex or javascript"? The answer can, and likely will, be *both*. – Sampson May 30 '12 at 05:43
  • @Learner : Yes i know. I mean to say i dont want any complicated solution because it is pretty simple and can be done in few lines though am not able to do it properly – user850234 May 30 '12 at 05:48
  • 1
    @user850234 Then show us your solution and we will help you figure out the problem. That will help you to learn the language and we won't have to do YOUR work. – Andreas May 30 '12 at 05:54
  • @Andreas : Please check the update in my question. – user850234 May 30 '12 at 05:56
  • @Learner : I have added what i have tried in my question – user850234 May 30 '12 at 05:59
  • [This may be handy for you.](http://stackoverflow.com/a/149099/1331430) Even though the function's name is "formatMoney", it doesn't add a `$`, and you can choose the decimal separator, the character added every 3 digits and how many decimals. You might have a problem with fixed decimals, but nothing you can't fix I guess. – Fabrício Matté May 30 '12 at 06:05
  • Oh never mind I just noticed you want comma every 2 digits except for the last 3 digits before the decimals. – Fabrício Matté May 30 '12 at 06:13
  • @FabrícioMatté Is it not possible to get number formatted as `7,12,34,56,789` . I can ignore decimal values – user850234 May 30 '12 at 06:14
  • Not sure if it can be done with one regex, or if it even makes sense to limit yourself to that technique. How about removing the last digit, then insert commas, then re-insert the last digit? – user123444555621 May 30 '12 at 06:29

4 Answers4

11

The result will depend on your browsers locale. But this might be an acceptable solution:

(7123456789.56742).toLocaleString();

Outputs:

7,123,456,789.56742

Try it and see if it outputs 7,12,34,56,789.567421 in your locale.

row1
  • 5,568
  • 3
  • 46
  • 72
4

Here's a function to convert a number to a european (1.000,00 - default) or USA (1,000.00) style:

function sep1000(somenum,usa){
  var dec = String(somenum).split(/[.,]/)
     ,sep = usa ? ',' : '.'
     ,decsep = usa ? '.' : ',';
  return dec[0]
         .split('')
         .reverse()
         .reduce(function(prev,now,i){
                   return i%3 === 0 ? prev+sep+now : prev+now;}
                )
         .split('')
         .reverse()
         .join('') +
         (dec[1] ? decsep+dec[1] :'')
  ;
}

Alternative:

function sep1000(somenum,usa){
  var dec = String(somenum).split(/[.,]/)
     ,sep = usa ? ',' : '.'
     ,decsep = usa ? '.' : ',';

  return xsep(dec[0],sep) + (dec[1] ? decsep+dec[1] :'');

  function xsep(num,sep) {
    var n = String(num).split('')
       ,i = -3;
    while (n.length + i > 0) {
        n.splice(i, 0, sep);
        i -= 4;
    }
    return n.join('');
  }
}
//usage for both functions
alert(sep1000(10002343123.034));      //=> 10.002.343.123,034
alert(sep1000(10002343123.034,true)); //=> 10,002,343,123.034

[edit based on comment] If you want to separate by 100, simply change i -= 4; to i -= 3;

function sep100(somenum,usa){
  var dec = String(somenum).split(/[.,]/)
     ,sep = usa ? ',' : '.'
     ,decsep = usa ? '.' : ',';

  return xsep(dec[0],sep) + (dec[1] ? decsep+dec[1] :'');

  function xsep(num,sep) {
    var n = String(num).split('')
       ,i = -3;
    while (n.length + i > 0) {
        n.splice(i, 0, sep);
        i -= 3;  //<== here
    }
    return n.join('');
  }
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177
3

use toLocaleString(); It automatically handles inserting commas and will also handle uk strings the right way

e.g. var num=63613612837131; alert(num.toLocaleString());

Mily Dahlke
  • 239
  • 2
  • 5
0

Below is the snippet of code, can be done in better way but this works :D

function formatDollar(num) 
{
var p = num.toFixed(2).split(".");
var chars = p[0].split("").reverse();
var sep1000 = false;
var newstr = '';
var count = 0;
var count2=0;
for (x in chars) 
{ 
count++;
if(count%3 == 1 && count != 1 %% !sep1000) 
{ 
newstr = chars[x] + ',' + newstr;
sep1000=true;
} 
else 
{ 
if(!sep1000)
{
newstr = chars[x] + ',' + newstr;
}
else
{
count2++;
if(count%2 == 0 && count != 1) 
{ 
newstr = chars[x] + ',' + newstr;
} 
else 
{ 
 newstr = chars[x] + newstr;
}
}
}
}
return newstr + "." + p[1]; 
}
Malcolm
  • 1,801
  • 3
  • 21
  • 48