본문 바로가기

JavaScript

숫자를 화폐 형식으로 표현해보자!

Date.prototype.toLocaleString() 활용하기

toLocalString() 메소드를 이용하면 화폐 단위를 손쉽게 나타낼 수 있다.
해당 메소드는 매개변수로 locales, options 두 가지를 갖는다. Intl.DateTimeFormat() 생성자의 매개변수와 일치한다.
locales 에는 화폐 단위를 정하고, options 에는 출력 형식을 지정한다.

🌝 예시

const number = 123456.789;

// request a currency format
console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
// → 123.456,79 €

// the Japanese yen doesn't use a minor unit
console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// → ¥123,457

 

예시보다 더 많은 옵션을 부여할 수 있다. 아주 일부만 적었다.

옵션 이름 해석
maximumFractionDigits
최대 소숫점 자리 수
roundingMode
숫자 어림 규칙

ceil, floor, expand, trunc, halfCeil, halfFloor, halfExpand(default), halfTrunc, halfEven

 

🌐 참고 문서

화폐 단위 Currency code (한국 : ko-KR)
https://docs.1010data.com/1010dataReferenceManual/DataTypesAndFormats/currencyUnitCodes.html

 

Currency codes (ISO 4217)

The following table provides a list of valid 4217 letter codes. Table 1. ISO 4217 Codes Entity Currency Code Minor Unit AFGHANISTAN Afghani AFN 2 ÅLAND ISLANDS Euro EUR 2 ALBANIA Lek ALL 2 ALGERIA Algerian Dinar DZD 2 AMERICAN SAMOA US Dollar USD 2 ANDORR

docs.1010data.com

언어 태그 Language tag (한국 : KRW)
https://www.techonthenet.com/js/language_tags.php

 

JavaScript: Language Tags (BCP 47)

JavaScript: Language Tags (BCP 47) BCP 47 Language Tags is the Internet Best Current Practices (BCP) for language tags. The purpose of these language tags is to establish codes to help identify languages both spoken and written. A language tag is composed

www.techonthenet.com

 

이 외에도 퍼센트, 십진법, 단위까지도 표현할 수 있다.

new Intl.NumberFormat("en-US", {
  style: "unit",
  unit: "liter",
}).format(amount); // '3,500 L'

new Intl.NumberFormat("en-US", {
  style: "percent",
  signDisplay: "exceptZero",
}).format(0.55);
// '+55%'

 

'JavaScript' 카테고리의 다른 글

정규식으로 원하는 문자열 잘라서 바꾸기  (0) 2021.11.14
keydown, keypress, keyup 차이  (0) 2021.10.21
const vs Object.freeze  (0) 2021.09.29