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

วิธีจัดรูปแบบตัวเลขเป็นสตริงสกุลเงินดอลลาร์ใน JavaScript

ใช้ Intl.NumberFormat ซึ่งเป็นส่วนหนึ่งของ Internationalization API เพื่อจัดรูปแบบตัวเลขเป็นสกุลเงินได้อย่างง่ายดายและแม่นยำ

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
  <body>
    <p>จัดรูปแบบ 150 เป็นดอลลาร์สหรัฐ (US$):</p>
    <script>
      var formatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 2,
      });
      // สำหรับ 150$
      document.write(formatter.format(150));
    </script>
  </body>
</html>

ตัวเลือกการจัดรูปแบบเพิ่มเติม

ตัวเลือก คำอธิบาย ตัวอย่าง
style: 'currency' แสดงเป็นสกุลเงิน $150.00
currency: 'USD' ระบุสกุลเงิน (ISO 4217) USD, EUR, THB, JPY
minimumFractionDigits: 2 จำนวนทศนิยมขั้นต่ำ 150.00
maximumFractionDigits: 0 จำนวนทศนิยมสูงสุด 150
currencyDisplay: 'symbol' แสดงสัญลักษณ์ (ค่าเริ่มต้น) $150.00
currencyDisplay: 'code' แสดงรหัสสกุลเงิน USD 150.00
currencyDisplay: 'name' แสดงชื่อเต็ม 150.00 US dollars

ตัวอย่างสกุลเงินอื่นๆ

// บาทไทย
var thbFormatter = new Intl.NumberFormat('th-TH', {
  style: 'currency',
  currency: 'THB'
});
console.log(thbFormatter.format(150)); // ฿150.00

// ยูโร
var eurFormatter = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR'
});
console.log(eurFormatter.format(150)); // 150,00 €

// เยนญี่ปุ่น (ไม่มีทศนิยม)
var jpyFormatter = new Intl.NumberFormat('ja-JP', {
  style: 'currency',
  currency: 'JPY',
  maximumFractionDigits: 0
});
console.log(jpyFormatter.format(150)); // ¥150

การรองรับเบราว์เซอร์

Intl.NumberFormat รองรับในเบราว์เซอร์สมัยใหม่ทุกตัว (Chrome 24+, Firefox 29+, Safari 10+, Edge 12+)