ใช้ 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
รูปแบบอื่นๆ
| Format Spec | ตัวอย่าง | ผลลัพธ์ |
|---|---|---|
| 1234567 | 1,234,567 | |
| 1234.5 | 1,234.50 | |
| 1234.56 | 1,235 | |
| 1234567 | 1_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 เพิ่ม