Just Do IT!

[JavaScript] Intl API 사용하기 (숫자 천단위마다 콤마 찍기) 본문

개발 공부/JavaScript

[JavaScript] Intl API 사용하기 (숫자 천단위마다 콤마 찍기)

MOON달 2023. 4. 18. 16:12
728x90
반응형
Intl API란?

Intl 개체는 ECMAScript 국제화 API의 네임스페이스로, 언어 구분 문자열 비교, 숫자 형식, 날짜 및 시간 형식을 제공한다.

Intl API를 사용하면 각 나라의 언어와 표현에 맞게 날짜 혹은 시간 등을 표시해줄 수 있다.

 

참고: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl

 

Intl - JavaScript | MDN

The Intl namespace object contains several constructors as well as functionality common to the internationalization constructors and other language sensitive functions. Collectively, they comprise the ECMAScript Internationalization API, which provides lan

developer.mozilla.org

 

 

 

 

 

 

 

 

 

 

Intl.NumberFormat()

new Intl.NumberFormat().format()을 사용하면 숫자를 천단위로 나누어 콤마를 찍을 수 있다.

보통 가격을 작성할 때 사용하는 방법 중 하나이다.

 

const num = new Intl.NumberFormat().format("50000")
console.log(num)  // 50,000

 

이런 식으로 손쉽게 콤마를 찍어줄 수 있다.

이전에 생각한 방법은 정규식을 사용하는 방법이었는데, 검색하가다 알게 되었다.

 

그리고 각 나라별로도 숫자를 표현할 수 있는데, 아직 우리나라 버전은 지원하지 않는다.

console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// Expected output: "123.456,79 €"

// The Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// Expected output: "¥123,457"

// Limit to three significant digits
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));
// Expected output: "1,23,000"

 

자세한 내용은 아래 링크에서 더 자세히 알아볼 수 있다.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat

 

Intl.NumberFormat - JavaScript | MDN

The Intl.NumberFormat object enables language-sensitive number formatting.

developer.mozilla.org

 

 

 

 

 

 

 

 

 

 

RelativeTimeFormat

RelativeTimeFormat를 이용하면 각 나라의 언어에 맞게 N일 전 N days age 이렇게 시간을 나타낼 수 있다.

1시간 전, 3개월 전 등 상대적인 시간을 표기할 때 사용한다.

 

const relativeFormatter = new Intl.RelativeTimeFormat("ko", {
    numeric: "always",
  });

const ago = relativeFormatter.format(-1, "day");
const after = relativeFormatter.format(1, "day");
console.log(ago, after); // 1일 전 1일 후

format의 첫 인자는 상대적인 시간의 숫자를, 두 번째 인자는 날짜 단위를 넣으면 된다.

 

  • auto:그저께
  • always: n일 전, n일 후

 

 

더 자세한건 아래 링크를 통해 볼수 있다.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat

 

 

 

 

 

 

 

 

 

 

 

 

 


단순히 천 단위로 콤마 찍는걸 구글링하다가 새롭게 알게되어서 블로그에도 정리해본다! 나중에도 적절히 사용할 수 있을 것 같아서 좋은 공부 한 듯하다.  

728x90