What is the best way to format number variables with commas in javascript
I am running into an issue formatting a javascript number. What is the equivalent of this csharp code in javascript:
var cSharpNumber = 10000;
string formattedNumber = c开发者_开发百科SharpNumber.ToString("#,###"); //this should show 10,000
I would like to avoid having to bring in other plugins if possible
JavaScript doesn't provide any way to do this out of the box, so you will have to use some custom code. A quick google search turned up this, which looks good to me:
http://www.mredkj.com/javascript/nfbasic.html
I found that code a long time and it has been working fine since : http://phpjs.org/functions/number_format:481
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;
});
}
returned values:
235=235
999.99=999.99
'1200000'=1,200,000
12345=12,345
10652.23=10,652.23
精彩评论