Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a thousand seperator to a number in JavaScript? [duplicate]

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?

like image 583
js-coder Avatar asked Mar 16 '12 19:03

js-coder


People also ask

How do you print a number with commas as thousands separators in JavaScript?

To comma-separate thousands in a big number in JavaScript, use the built-in toLocaleString() method. It localizes the number to follow a country-specific number formatting. To separate thousands with commas, localize the number to the USA.

How do you convert a number to a comma separated string?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do you format numbers in JavaScript?

The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal. The toFixed() method is used with a number as shown in the above syntax using the '. ' operator.


2 Answers

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

like image 182
kennebec Avatar answered Nov 16 '22 04:11

kennebec


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.

like image 26
Rémi Breton Avatar answered Nov 16 '22 03:11

Rémi Breton