myhduck's Octopress Blog

I want fly well

Js Number Format

| Comments

JavaScript에서 천단위 콤마로 변경할때, 천단위 콤마 제거 할때
스트링에 프로토타입으로 정의 해놓으면 편하다

천단위 콤마로 변경
1
2
3
4
5
6
7
8
9
10
11
String.prototype.numberFormat = function(){
  var str = this;
  x = str.split(".");
  x1 = x[0];
  x2 = x.length > 1 ? "." + x[1] : "";
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
      x1 = x1.replace(rgx, "$1" + "," + "$2");
  }
  return x1 + x2;
}

천단위 콤마 제거
1
2
3
String.prototype.unNumberFormat = function(){
  return this.replace(/[^0-9-.]/g, "");
}

Comments