JavaScript >> Javascript 文檔 >  >> Tags >> string

如何在 JavaScript 中將數字格式化為貨幣字符串

在 JavaScript 中將數字格式化為貨幣字符串的最簡單和最流行的方法是使用 Internationalization API。它提供了對語言敏感的字符串比較、數字格式以及日期和時間格式的方法。

其中一種方法是 Intl.NumberFormat() ,這讓我們可以使用自己選擇的語言環境來格式化數字。

Intl.NumberFormat() 構造函數接受兩個參數。第一個參數是像 en-US 這樣的語言環境字符串 或 de-DE .第二個參數是一個對象,用於指定格式化時要應用的選項:

const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
})

console.log(formatter.format(100)) // $100.00
console.log(formatter.format(1255.786)) // $1,255.79
console.log(formatter.format(14567890)) // $14,567,890.00

在選項對像中,style 屬性用於指定格式的類型。它有以下可能的值:

  • decimal 用於純數字格式。
  • currency 用於貨幣格式。
  • unit 用於單位格式。
  • percent 用於百分比格式。

默認style 屬性值為 decimal .在上面的例子中,我們使用了 currency 將數字格式化為貨幣字符串。

currency 屬性允許您定義要在貨幣格式中使用的貨幣,例如 USD , EUR , 或 CAD .

最後,maximumSignificantDigitsmaximumSignificantDigits 屬性設置格式化時使用的最小和最大小數位數。

話雖如此,讓我們編寫一個通用函數,它接受一個數字值、一個可選的貨幣、區域設置、最小和最大小數位數並返回一個格式化的貨幣字符串:

const currency = (amount, currency = 'USD', locale = 'en-US', minfd = 2, maxfd = 2) => {
  return new Intl.NumberFormat(locale, {
    style: 'currency',
    currency: currency,
    minimumFractionDigits: minfd,
    maximumFractionDigits: maxfd
  }).format(amount)
}

現在我們可以使用上面的 currency() 將任意數字格式化為貨幣字符串的方法:

console.log(currency(100)) // $100.00
console.log(currency(14567890, 'CAD')) // CA$14,567,890.00
console.log(currency(1255.786, 'EUR', 'de-DE')) // 1.255,79 €

Tutorial JavaScript 教程
  1. 如何使用 jquery 或 javascript 對對像數組進行排序

  2. NodeJS 世界中的 PM2 和 Docker

  3. 獲取 API 101

  4. 了解 ES6 和現代 JavaScript

  5. 檢測到語言但翻譯不適用於 i18n

  6. 電子冒險:第 84 集:高性能十六進制編輯器

  7. 在 VueJS 上使用領導線

  1. 使用 CodeWrite 提升您的 Web 開發博客!

  2. 反應條件渲染

  3. 使用 JavaScript 異步加載腳本

  4. 再見2020,你好2021世界!!

  5. 從頭開始構建一個 React 應用程序(使用 create-react-app)! ⚛️

  6. 你不需要突變

  7. 帶有 Framer Motion 的動畫模態

  1. 使用 React 測試庫測試語義 UI React 輸入

  2. 5 個 JavaScript 控制台方法將提高您的調試技能🚀

  3. 使用 Github Pages 反應路由器💎

  4. 使用 Testem 讓 JavaScript 測試變得有趣