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

จัดรูปแบบตัวเลขด้วยคอมม่า (Thousand Separator) ใน Python

ใช้ f-string หรือ format() จัดรูปแบบตัวเลขให้มีคอมม่าคั่นพัน

จำนวนเต็ม (Integer)

print(f"{1445:,d}")      # 1,445
print(f"{140045:,d}")     # 140,045

ทศนิยม (Float)

print("{:,.2f}".format(3435.242563))  # 3,435.24
print(f"{1234567.89:,.2f}")            # 1,234,567.89

รูปแบบอื่นๆ

{:,}{:,.2f}{:,.0f}{:_} (Python 3.6+)
Format Specตัวอย่างผลลัพธ์
12345671,234,567
1234.51,234.50
1234.561,235
12345671_234_567

ใช้กับ locale (ภาษาไทย)

import locale
locale.setlocale(locale.LC_ALL, 'th_TH.UTF-8')
print(locale.format_string("%d", 1234567, grouping=True))
# 1,234,567 (ขึ้นอยู่กับระบบปฏิบัติการ)

สรุป

f-string {:,} หรือ {:,.2f} ใช้ง่ายที่สุด ไม่ต้อง import เพิ่ม