상황에 맞춰 쓸 수 있는 아주 유용한 함수
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;
}
Syntax
numberFormat(val, isMinus, isFloat, isComma)
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)">
'javascript' 카테고리의 다른 글
[javascript]사용자를 편의를 위한 숫자 콤마 찍기 구성 (0) | 2023.04.03 |
---|---|
[javascript] 유용하게 쓰이는 정규표현식들 (0) | 2023.03.27 |
[javascript] 정규표현식을 이용한 사업자 번호, 이메일 검증 (javascript버전) (0) | 2023.03.09 |
[javascript]javascript (INSERT, UPDATE 화면)에서 사용하는 함수 (0) | 2023.03.09 |
[javascript] javascript에 대해서 알아두기 (이론) (0) | 2023.03.09 |