자동 콤마 처리 예제: 사용자가 입력한 숫자에 쉬운 방법으로 콤마를 추가합니다.
숫자 콤마 처리하기
사용자가 숫자를 입력할때 마다 콤마를 자동으로 붙이는 예제입니다.
먼저 일반적으로 사용하는 콤마 제거하기, 붙이기는 아래와 같습니다.
콤마 붙이기
export function function numberWithCommas(x: number) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
콤마 제거하기
export function removeComma(val: number | string): number {
if (val !== undefined && val !== null) {
// here we just remove the commas from value
return parseFloat(val.toString().replace(/,/g, ''));
} else {
return val;
}
}
콤마 붙이기 대신 angular pipe중 number를 사용하여 아래 처럼 처리하면 사용자가 숫자를 입력시 자연스럽게 숫자에 컴마가 들어간다.
- html
<input type="text" placeholder="0" [ngModel]="amount | number" (ngModelChange)="onChange($event)">
- ts
public onChange(ev: any) {
this.amount=removeComma(ev);
}