javascript
[javascript] Intl 객체 총 정리
drxxn
2023. 8. 2. 02:00
- 목차
1. 숫자 표현하기
const n = 1234567;
const formatter = new Intl.NumberFormat('ko');
formatter.format(n) // '1,234,567'
const formatter = new Intl.NumberFormat('ko', {notation: 'compact'});
formatter.format(n) // '123만'
const formatter = new Intl.NumberFormat('en', {notation: 'compact'});
formatter.format(n) // '1.2M'
const formatter = new Intl.NumberFormat('en', {
notation: 'compact',
compactDisplay: 'long'
});
formatter.format(n) // '1.2 million'
const formatter = new Intl.NumberFormat(navigator.language, {
notation: 'compact',
compactDisplay: 'long'
});
formatter.format(n) // '1.2 million'
2. 가격 표현하기
const price = 1234567;
const formatter = new Intl.NumberFormat('ko', {
style: 'currency',
currency: 'krw',
notation: 'compact'
});
formatter.format(price) // '₩1만'
const formatter = new Intl.NumberFormat('ko', {
style: 'currency',
currency: 'krw'
});
formatter.format(price) // '₩1,234,567'
const formatter = new Intl.NumberFormat('ko', {
style: 'currency',
currency: 'usd',
notation: 'compact'
});
formatter.format(price) // '$12K'
3. 상대시간 표현하기
const formatter = new Intl.RelativeTimeFormat('en');
formatter.format(1, 'day'); // in 1 day
formatter.format(2, 'day'); // in 2 days
formatter.format(-1, 'day'); // 1 day ago
formatter.format(-2, 'day'); // 2 days ago
const formatter = new Intl.RelativeTimeFormat('en', {numeric: 'auto'});
formatter.format(1, 'day'); // tomorrow
formatter.format(2, 'day'); // in 2 days
formatter.format(-1, 'day'); // yesterday
formatter.format(-2, 'day'); // 2 days ago
const formatter = new Intl.RelativeTimeFormat('ko', {numeric: 'auto'});
formatter.format(1, 'day'); // 내일
formatter.format(2, 'day'); // 모레
formatter.format(-1, 'day'); // 어제
formatter.format(-2, 'day'); // 그저께
const formatter = new Intl.RelativeTimeFormat('ko', {numeric: 'auto'});
const today = new Date();
const createdAt = new Date(2023, 1, 1);
const pastDays = Math.ceil((createdAt - today) / (1000 * 60 * 60 * 24));
formatter.format(pastDays, 'day'); // 182일 전