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?
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.
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.
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.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With