반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

그럴 수도 있지

[Javascript] 숫자만 입력, 마이너스, 소수점, 콤마 (Enter only numbers, minus, decimal point, comma) 본문

Javascript

[Javascript] 숫자만 입력, 마이너스, 소수점, 콤마 (Enter only numbers, minus, decimal point, comma)

디벅 2022. 6. 24. 22:58
반응형



숫자만 입력을 받아야 하거나, 마이너스 혹은 플러스만. 소수점 입력이 가능하거나 혹은 불가능하거나. 천단위가 넘어가면 콤마 처리를 해줘야하거나.

 

결국엔 인터넷에서 보고 배운 걸 합쳐서 함수를 만들었고 유용하게 사용 중이다. 회사에서 제일 많이 사용 중인 함수 중 하나. 

 

* 예제는 아래에 간단하게 설명

 

Syntax

numberFormat(val, isMinus, isFloat, isComma)

 

Javascript

//숫자 입력 (마이너스, 소수점, 콤마)
function numberFormat(val, isMinus, isFloat, isComma){
  var str = val;
  //일단 마이너스, 소수점을 제외한 문자열 모두 제거
  str = str.replace(/[^-\.0-9]/g, '');
  //마이너스
  if(isMinus){
     str = chgMinusFormat(str);   
  } else {
     str = str.replace('-','');
  }
  
  //소수점
  if(isFloat){
     str = chgFloatFormat(str);       
  } else {
     if(!isMinus ){
        str = str.replace('-','');
     }
     str = str.replace('.','');
     if(str.length>1){
        str = Math.floor(str);
        str = String(str);
     }
  }
  
  //콤마처리
  if(isComma){
     var parts = str.toString().split('.');
     if(str.substring(str.length - 1, str.length)=='.'){
        str = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g,",") +".";
     } else {
        str = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g,",") + (parts[1] ? "." + parts[1] : "");
     }
  }

  return str;
}

function chgFloatFormat(str){
  var idx = str.indexOf('.');  
  if(idx<0){  
     return str;
  } else if(idx>0){
     var tmpStr = str.substr(idx+1);    
     if(tmpStr.length>1){             
        if(tmpStr.indexOf('.')>=0){        
           tmpStr =  tmpStr.replace(/[^\d]+/g, '');                  
           str = str.substr(0,idx+1) + tmpStr;
        }
     }    
  } else if(idx==0){
        str = '0'+str;
  }
  return str;  
}
  
function chgMinusFormat(str){
  var idx = str.indexOf('-');
  if(idx==0){
  var tmpStr = str.substr(idx+1);
     //뒤에 마이너스가 또 있는지 확인
     if(tmpStr.indexOf('-')>=0){
           tmpStr = tmpStr.replace('-','');
        str = str.substr(0,idx+1) + tmpStr;  
     }
  } else if(idx>0){
        str = str.replace('-','');
  } else if(idx<0){
        return str;
  }
     return str;
}

 

example 

1. 숫자만 입력, 마이너스 허용, 소수점 허용, 콤마 처리) 

<input type='text' onkeyup = "this.value=numberFormat(this.value, true, true, true)">

 

2. 숫자만 입력 받으며, 마이너스 허용, 소수점 불가, 콤마 처리

<input type='text' onkeyup = "this.value=numberFormat(this.value, true, false, true)">

 

3. 오로지 숫자만 입력 받으며 마이너스, 소수점, 콤마 처리 안함

<input type='text' onkeyup = "this.value=numberFormat(this.value, false, false, true)">

 

4. 숫자만 입력 받으며 마이너스 허용, 소수점 불가, 콤마 처리 안함

<input type='text' onkeyup = "this.value=numberFormat(this.value, true, false, false)">

 

위와 같이 입맛에 따라 파라미터 값을 넘겨 사용하면 된다.

 

* 예제 파일

numberFormat.html
0.00MB
numberFormat.js
0.00MB

 

반응형