Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Định dạng số thành chuỗi tiền tệ USD trong JavaScript


Để format số thành chuỗi tiền tệ (USD), dùng Intl.NumberFormat (Internationalization API) - chuẩn built-in, không cần thư viện ngoài.

Ví dụ cơ bản

<!DOCTYPE html>
<html>
  <body>
    <p>Format 150 as US dollars (US$):</p>
    <script>
      var formatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 2
      });
      document.write(formatter.format(150)); // $150.00
    </script>
  </body>
</html>

Các tùy chọn quan trọng

const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',           // 'currency' | 'decimal' | 'percent' | 'unit'
  currency: 'USD',             // ISO 4217 code: USD, EUR, VND, JPY...
  currencyDisplay: 'symbol',   // 'symbol' ($) | 'code' (USD) | 'name' (US dollars) | 'narrowSymbol' ($)
  minimumFractionDigits: 2,    // Số chữ số thập phân tối thiểu
  maximumFractionDigits: 2,    // Số chữ số thập phân tối đa
  useGrouping: true            // Dấu phân cách nghìn (1,000)
});

// Ví dụ VND
const vnd = new Intl.NumberFormat('vi-VN', {
  style: 'currency',
  currency: 'VND',
  minimumFractionDigits: 0 // VND thường không có cent
});
vnd.format(1500000); // "1.500.000₫"

Hỗ trợ Locale

const price = 123456.789;

new Intl.NumberFormat('en-US', {style:'currency', currency:'USD'}).format(price); // $123,456.79
new Intl.NumberFormat('de-DE', {style:'currency', currency:'EUR'}).format(price); // 123.456,79 €
new Intl.NumberFormat('ja-JP', {style:'currency', currency:'JPY'}).format(price); // ¥123,457
new Intl.NumberFormat('vi-VN', {style:'currency', currency:'VND'}).format(price); // 123.457₫
new Intl.NumberFormat('ar-SA', {style:'currency', currency:'SAR'}).format(price); // ١٢٣٬٤٥٦٫٧٩ ر.س.

Performance: Reuse Formatter

// ❌ Tạo mới mỗi lần - chậm
function formatPrice(price) {
  return new Intl.NumberFormat('en-US', {style:'currency', currency:'USD'}).format(price);
}

// ✅ Tạo một lần, reuse
const usdFormatter = new Intl.NumberFormat('en-US', {style:'currency', currency:'USD'});
function formatPrice(price) {
  return usdFormatter.format(price);
}

Browser Support

Hỗ trợ tốt mọi browser hiện đại (IE11+). Node.js: cần ICU data (full-icu) cho locale non-English.