티스토리 뷰

728x90

숫자 "123"이 있을 때, 7자리로 표현하면서 앞을 0으로 채우거나 뒤를 0으로 채워야 하는 경우가 있을 수 있습니다.

 

예를 들어, "123"은 "0000123" 처럼 앞을 0으로 채울 수 있고 또는 "1230000"으로 뒤를 0으로 채워 7자리를 만들 수 있습니다.

 

숫자 앞, 또는 뒤에 0으로 특정 자리수 만큼 채우는 방법에 대해서 알아보겠습니다.

 

숫자 앞 0으로 채우기

string.padStart(N, A)은 문자열 string의 N자리에서 비어있는 부분을 A로 채웁니다. 예를 들어, string의 길이가 1이면, 길이가 N이 될 때까지 A 반복하여 채웁니다.

아래 예제에서 숫자가 8이면, padStart(5, "0")는 5자리를 맞추기 위해 0을 4개 추가하여 "00008"을 리턴합니다. 아래 예제를 보시면 어떻게 동작하는지 알 수 있습니다.
const num = 8;
let result = num.toString().padStart(2, "0");
console.log(result); // "08"

result = num.toString().padStart(3, "0");
console.log(result); // "008"

result = num.toString().padStart(4, "0");
console.log(result); // "0008"

result = num.toString().padStart(4, "X");
console.log(result); // "XXX8"

Output:

08
008
0008
XXX8

 

숫자 뒤 0으로 채우기

padEnd(N, A)는 padStart()와 반대로, 정해진 자릿수만큼 비어있으면 문자열 뒤를 A로 채웁니다.

 

아래와 같이 구현할 수 있습니다. 부족한 개수만큼 특정 문자로 채울 수 있습니다.

const num = 8;
let result = num.toString().padEnd(2, "0");
console.log(result); // "08"

result = num.toString().padEnd(3, "0");
console.log(result); // "008"

result = num.toString().padEnd(4, "0");
console.log(result); // "0008"

result = num.toString().padEnd(4, "X");
console.log(result); // "XXX8"

Output:

80
800
8000
8XXX
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/03   »
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
글 보관함