Regular Expression for formatting numbers in JavaScript

前端 未结 14 1510
遥遥无期
遥遥无期 2020-11-30 19:35

I need to display a formatted number on a web page using JavaScript. I want to format it so that there are commas in the right places. How would I do this with a regular exp

14条回答
  •  没有蜡笔的小新
    2020-11-30 20:16

    // You might want to take decimals into account

    Number.prototype.commas= function(){
     var s= '', temp, 
     num= this.toString().split('.'), n=num[0];
     while(n.length> 3){
      temp= n.substring(n.length-3);
      s= ','+temp+s;
      n= n.slice(0, -3);
     }
     if(n) s= n+s;
     if(num[1]) s+='.'+num[1];
     return s;
    }
    

    var n= 10000000000.34;

    n.commas() = returned value: (String) 10,000,000,000.34

提交回复
热议问题