จัดรูปแบบตัวเลขทศนิยมให้กว้างคงที่ใน Python ด้วย format function บนสตริง
ตัวอย่าง
nums = [0.555555555555, 1, 12.0542184, 5589.6654753]
for x in nums:
print("{:10.4f}".format(x))
ผลลัพธ์
0.5556 1.0000 12.0542 5589.6655
ตัวอย่าง
ใช้ฟังก์ชันเดียวกันจัดรูปแบบ integer ได้
nums = [5, 20, 500]
for x in nums:
print("{:d}".format(x))
ผลลัพธ์
5 20 500
ตัวอย่าง
ให้ padding ด้วยระบุตัวเลขหน้า d
nums = [5, 20, 500]
for x in nums:
print("{:4d}".format(x))
ผลลัพธ์
5 20 500
เว็บไซต์ https://pyformat.info/ เป็นแหล่งข้อมูลดีสำหรับเรียนรู้การจัดรูปแบบตัวเลขใน Python