9

Possible Duplicate:
How to format numbers using javascript?

I want to add a thousand seperator, like ., to a number in JavaScript.

1000 -> 1.000
1000000 -> 1.000.000

What is the most elegant way to do that?

3

5 Answers 5

21

I don't know about elegant...

function addCommas(n){
    var rx=  /(\d+)(\d{3})/;
    return String(n).replace(/^\d+/, function(w){
        while(rx.test(w)){
            w= w.replace(rx, '$1,$2');
        }
        return w;
    });
}

addCommas('123456789456.34');

returned value: (String) 123,456,789,456.34

6

Try such a Regexp:

function formatNumber(num)
{
    return ("" + num).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, function($1) { return $1 + "." });
}

alert(formatNumber(100000));

​ To be honest, I found it here, while was trying to solve your problem.

3

Here's my take (just for fun):

var num = 1000000;
var cnt = 0; // temp counter. 
var s = String(num).split('').
                    reverse().
                    map(function(v) { 
                        if (cnt < 2) {
                            cnt += 1; 
                            return v;
                        } else {
                            cnt = 0; 
                            return ',' + v;
                        }
                    }).
                    reverse().
                    join('');
// 1,000,000
3

You can use following code to do the job:

(10000000 + "").split('').reverse().map(function (value, i) {
    return (!(i % 3)) ? "." + value : value;
}).reverse().join('');
2

Here is a function to add commas, found here: http://www.mredkj.com/javascript/nfbasic.html

function addCommas(nStr)
{
    var sep = ',';
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + sep + '$2');
    }
    return x1 + x2;
}

I modified the code a bit to add var sep = ',';, so you can change your separator easily, depending on the language.

1
  • Much thanks! I changed the var sep = ','; to var sep = '.'; and use it like this: addCommas(price.toFixed(2).replace('.',',')) to get the format like this: 3.426,00 Feb 25, 2019 at 12:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.