จะปัดค่าเป็นทศนิยม 2 ตำแหน่งใน Python ยังไง? คำถามดีมาก Python มี functions ให้ปัดตัวเลข
การปัดทศนิยม 2 ตำแหน่งพบบ่อย เงินใช้แค่ 2 ตำแหน่ง ไม่ต้องการ process ค่าเงินกับตำแหน่งที่ 3 น้ำหนักมักแสดง 2 ตำแหน่ง ค่าเพิ่มเติมเป็น precision ที่ไม่จำเป็นในส่วนใหญ่
คู่มือนี้พูดถึงวิธีปัดตัวเลข 2 ตำแหน่งใน Python พร้อม 2 code snippets ช่วยคุณปัดตัวเลขในโค้ดของตัวเอง
ปัดตัวเลขด้วย round()
เขียนโปรแกรมคำนวณว่าแต่ละเพื่อนในกลุ่มต้องจ่ายค่าอาหารเย็นเท่าไหร่ เริ่มถามผู้ใช้ราคาอาหารและจำนวนเพื่อน:
meal_cost = input("How much did your meal cost? ")
friends = input("How many friends were with you? ")
คำนวณว่าแต่ละเพื่อนต้องจ่ายเท่าไหร่ สมมติจ่ายเท่ากันทุกคน ไม่ว่าจะสั่งอะไร:
cost_per_friend = float(meal_cost) / float(friends)
แปลง "meal_cost" และ "friends" เป็น floating point เพราะ input() คืนค่า string ไม่สามารถคำนวณทางคณิตศาสตร์กับ string ด้วย math operators ของ Python ได้
ปัดค่าเป็น 2 ตำแหน่ง ใช้ round() method เมธอด round() ปัดค่าเป็น nearest integer หรือ nearest decimal place
พิมพ์จำนวนที่แต่ละเพื่อนต้องจ่าย:
rounded_value = round(cost_per_friend, 2)
print("Each friend must pay $" + str(rounded_value) + " for dinner.")
ใช้ built-in round() ปัด "cost_per_friend" เป็น 2 ตำแหน่ง ใช้ string concatenation สร้างข้อความพิมพ์คอนโซล บอกว่าแต่ละเพื่อนจ่ายเท่าไหร่
รันโค้ด:
How much did your meal cost? 64.92 How many friends were with you? 6 Each friend must pay $10.82 for dinner.
ถ้าหาร 64.92 ด้วย 6 โดยไม่ปัด จะได้ตัวเลขทศนิยมมาก โค้ดคำนวณแต่ละคนจ่าย $10.82 โดยปัดผลหารเป็น 2 ตำแหน่ง
ปัดตัวเลขด้วย String Formatting
ตัวอย่างก่อน แสดง rounded number ใน string มีอีกวิธีปัดถ้าวัตถุประสงค์คือแสดงใน string วิธีนี้รองรับเฉพาะ Python 3.x
ปรับโค้ดปัดค่าที่แต่ละเพื่อนจ่าย ด้วย .format() string formatting syntax
เริ่มคำนวณค่าที่แต่ละเพื่อนจ่าย:
meal_cost = input("How much did your meal cost? ")
friends = input("How many friends were with you? ")
cost_per_friend = float(meal_cost) / float(friends)
เขียน print() แจ้งค่าที่แต่ละเพื่อนจ่าย ใช้ .format() กับ print() จัดรูปแบบค่าใน string:
print("Each friend must pay ${:0.2f} for dinner.".format(cost_per_friend))
.format() ใช้ syntax นี้สร้าง decimal representation ปัด 2 ตำแหน่ง:
{:0.2f}
Colon (:) บอกว่า format value Zero ทำให้ Python รู้ว่า deal กับ number ที่อาจ pad zeros .2 สั่ง Python ปัด 2 ตำแหน่ง "f" แสดง value เป็น number
รันโค้ด:
How much did your meal cost? 64.92 How many friends were with you? 6 Each friend must pay $10.82 for dinner.
โค้ดคำนวณสำเร็จ ผลลัพธ์เหมือน snippet แรก มี 2 หลักหลังทศนิยม แสดงว่าปัด 2 ตำแหน่งแล้ว
วิธีนี้มีประสิทธิภาพกว่า snippet แรก เพราะแค่ต้องการพิมพ์ค่า ในโค้ดนี้ไม่ได้ใช้ round() statement
ถ้าตั้งใจใช้ rounded value ต่อในโค้ด string formatting syntax จะไม่คุ้มค่า
สรุป
วิธีทั่วไปปัดค่า 2 ตำแหน่ง:
- ใช้
round()method - ใช้ string formatting
วิธีแรกดีสำหรับทุกกรณีที่ต้องปัดตัวเลข วิธีที่สองใช้ได้เฉพาะต้องการปัดค่าเพื่อใช้ใน string และใช้ Python 3.x
ตอนนี้คุณพร้อมปัดค่า 2 ตำแหน่งในโค้ดอย่าง Python pro แล้ว!