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?
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?
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
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
You can use following code to do the job:
(10000000 + "").split('').reverse().map(function (value, i) {
return (!(i % 3)) ? "." + value : value;
}).reverse().join('');
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.