반응형
자바스크립트에서 언어에 맞는 숫자 서식을 변경하고자 할 때 유용하게 사용하는 내장된 표준 객체인 Intl.NumberFormat의 활용법에 대해 알아 보겠습니다.
1. 나라별 통화 표기 하기
- 한화 표기는 나라 형식에 'ko-KR' 을 적용
const number = 123456.789;
// 통화 서식
console.log(
new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(
number,
),
);
// → 123.456,79 €
// 한국 원화는 보조 통화 단위를 사용하지 않음
console.log(
new Intl.NumberFormat("ko-KR", { style: "currency", currency: "KRW" }).format(
number,
),
);
// → ₩123,457
// 유효숫자를 세 개로 제한
console.log(
new Intl.NumberFormat("en-IN", { maximumSignificantDigits: 3 }).format(
number,
),
);
// → 1,23,000
옵션을 지정하면 언어 뿐만아니라 표출되는 자릿수 등을 조정할 수 있습니다.
아래 예시는 금액에 $ 표시와 소숫점 2자리로 잘라서 표출하도록 합니다.
const formatter = new
Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
// 사용예
formatter.format(yourValue);
2. 날짜 포맷 표기하기
- 나라별 날짜 포맷에 맞춰 변경
const date = new Date('2022-10-25 19:30:00');
new Intl.DateTimeFormat('en-US').format(date);
new Intl.DateTimeFormat('ko-KR').format(date);
new Intl.DateTimeFormat('ja-JP').format(date);
아래와 같이 지역 locale 설정에 따라 결과가 다르게 표출
'10/25/2022' // en-US
'2022. 10. 25.' // ko-KR
'2022/10/25' // ja-JP
- 년, 월, 일, 시, 분, 초 등 각 단위의 형식 또한 옵션으로 지정
const date = new Date('2022-10-25 19:30:00');
const options = {
year: "2-digit",
month: "short",
weekday: "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: true
}
console.log(new Intl.DateTimeFormat('en-US', options).format(date));
console.log(new Intl.DateTimeFormat('ko-KR', options).format(date));
결과는 아래와 같습니다.
'Tue, Oct 25, 22, 7:30:00 PM' // en-US
'22년 10월 25일 (화) 오후 7:30:00' // ko-KR
24시간 형식으로 변경 하려면 옵션중에서 hour12 : false 로 변경하면 됩니다.
'Tue, Oct 25, 22, 19:30:00' // en-US
'22년 10월 25일 (화) 19시 30분 0초' // ko-KR
반응형
'자바스크립트(Javascript)' 카테고리의 다른 글
MongoDB에 데이터 일괄 업로드 하기(2) (1) | 2023.12.22 |
---|---|
MongoDB에 데이터 일괄 업로드 하기(1) (1) | 2023.12.21 |
Pagination 기능 만들기 (0) | 2023.11.03 |
텍스트필드 데이터 줄이거나 줄바꿈 표현하기 (1) | 2023.11.01 |
회원가입시 패스워드 유효성(Validation) 검사하기 (1) | 2023.10.28 |