Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript Format Currency: ใช้ Intl.NumberFormat จัดรูปแบบเงิน

ใน JavaScript ใช้ Intl.NumberFormat() constructor ระบุ currency ที่ต้องการให้ number แทน ใช้ property style: 'currency' เพื่อจัดรูปแบบเงิน

Constructor และ Parameters

new Intl.NumberFormat([locales[, options]])

เพราะเป็น constructor ต้องใช้ keyword new สร้าง object สำหรับ specialized number formatting

รับ 2 optional parameters:

  • locales: string ตาม BCP 47 language tags (เช่น en-US สำหรับอังกฤษ-US, pt-BR โปรตุเกส-บราซิล, th-TH ไทย)
  • options: object มี properties มากกว่า 17 ตัว เน้น 3 ตัวสำคัญ: style, currencyDisplay, currencySign

ตัวอย่างโค้ดพื้นฐาน

const money = 85000.50;

// บราซิล Real (BRL)
console.log(new Intl.NumberFormat('pt-BR', {
  style: 'currency',
  currency: 'BRL'
}).format(money)); // R$85.000,50

// USD
console.log(new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD'
}).format(money)); // $85,000.50

// Japanese Yen (JPY) - ไม่มี minor units ปัดเศษ
console.log(new Intl.NumberFormat('ja-JP', {
  style: 'currency',
  currency: 'JPY'
}).format(money)); // ¥85,001

ใช้ format() method ส่ง money variable เข้าไปหลังสร้าง object formatter แล้ว สังเกต symbol และ format ถูกต้องตาม locale แต่ละประเทศ

currencyDisplay และ currencySign

currencyDisplay

แสดง currency ในรูปแบบต่างๆ: symbol, narrowSymbol, code, name

let money = 85000.50;

const symbol = new Intl.NumberFormat('en-US', {
  style: 'currency', currency: 'USD', currencyDisplay: 'symbol'
}).format(money); // $85,000.50

const narrowSymbol = new Intl.NumberFormat('en-US', {
  style: 'currency', currency: 'USD', currencyDisplay: 'narrowSymbol'
}).format(money); // $85,000.50

const code = new Intl.NumberFormat('en-US', {
  style: 'currency', currency: 'USD', currencyDisplay: 'code'
}).format(money); // USD 85,000.50

const name = new Intl.NumberFormat('en-US', {
  style: 'currency', currency: 'USD', currencyDisplay: 'name'
}).format(money); // 85,000.50 US dollars

currencySign: accounting

wrap ตัวเลขลบในวงเล็บแทนเครื่องหมายลบ ใช้กับ accounting ต้องตั้ง option เป็น 'accounting' (default เป็น 'standard')

let money = -8500.50;
const accounting = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  currencySign: 'accounting'
}).format(money);
console.log(accounting); // ($8,500.50)

สรุป

Intl.NumberFormat() เป็น constructor สำหรับ format currency (และ number อื่นๆ) ใน property style ใช้ร่วมกับ format() แสดงเงินตามต้องการ รองรับ locales หลากหลายและ options ครบครัน